Service Worker 101 (en)

  • Published on
    13-Apr-2017

  • View
    466

  • Download
    0

Embed Size (px)

Transcript

  • ServiceWorker101@cwdoh,GDEforWeb

    1

    https://twitter.com/cwdoh

  • WebWorker

    2

  • Whatwillhappenfromthefollowingcode:

    vartill=Date.now()+5000;

    while(Date.now()

  • Freeeee...eeeeze!!!

    Can'tdoanythingsuchasscroll,click,...

    4

  • YourJavaSciptcodesrunsonUIthread

    Itmeansthatyourcodealwaystrytoblockrenderingunderyourcontrol.:p

    5

  • Longqueuemakesothersunhappy. 6

  • WebWorkerwillrescueyourbrowser

    Yeah,ifyouwroterightcodes,andfindnicecustomersusingmodernbrowser...probably...

    7

  • WebWorkers

    AnAPIthatallowstospawnbackgroundworkersrunningscriptsinparalleltotheirmainpage.Thisallowsforthreadlikeoperationwithmessagepassingasthecoordinationmechanism.

    8

    https://www.w3.org/TR/workers/

  • WebWorkerisabrowserfeaturefor

    Runningscripts:

    threadlikelyinBackgroundwithmessagepassing

    9

  • CommonrulesofWebWorker

    HasownglobalscopeCan'tdirectlymanipulatetheDOMCan'tuseallofpropertiesandmethodinwindowscope

    10

  • Code

    Threadlikeoperationwithmessagepassing

    fetch('myencrypeddoc.txt').then(function(res){//spawnworkervarworker=newWorker('decorder.js');worker.onmessage=function(e){console.log('Decoded:'+e.data);};//decodeblobdatawithworkerworker.postMessage([res.clone().blob()]);});

    decorder.js

    onmessage=function(e){//decode...postMessage(decodedResult);};

    11

  • SharedWorker

    12

  • SharedWorker

    Aspecifickindofworkerthatcanbeaccessedfromseveralbrowsingcontexts,suchasseveralwindows,iframesorevenworkers.Theyimplementaninterfacedifferentthandedicatedworkersandhaveadifferentglobalscope,SharedWorkerGlobalScope.

    13

    https://developer.mozilla.org/en-US/docs/Web/API/SharedWorkerhttp://w3c.github.io/html/browsers.html#sec-browsing-contextshttps://developer.mozilla.org/en-US/docs/Web/API/SharedWorkerGlobalScope

  • SharedWorkerisaspecifickindofworker:

    AccessiblefromseveralbrowsingcontextsDifferentinterfaceDifferentglobalscope

    14

  • Usallywecalldedicatedworker,ifit'snotshared.

    15

  • ServiceWorker

    16

  • W3CSpecification:

    Amethodthatenablesapplicationstotakeadvantageofpersistentbackgroundprocessing,includinghookstoenablebootstrappingofwebapplicationswhileoffline.

    17

    https://www.w3.org/TR/service-workers/

  • ThecoreofthissystemisaneventdrivenWebWorker,whichrespondstoeventsdispatchedfromdocumentsandothersources.

    18

  • Asystemformanaginginstallation,versions,andupgradesisprovided.

    19

  • TheserviceworkerisagenericentrypointforeventdrivenbackgroundprocessingintheWebPlatformthatisextensiblebyotherspecifications.

    20

  • ServiceWorkerisanothertypeofworkerforpersistentbackgroundprocessing

    HavinganeventdrivenmodelManaginginstallation,versionsandupgradesGenericentrypointforotherspecifications

    21

  • Dedicated/SharedWorkervsServiceWorker

    22

  • DedicatedWorker&SharedWorker:Runtime,Creation,Browsingcontext

    Athreadlikethingscanbecreatedatruntime.

    YoushouldcreateWorkerandcontrolitatruntime.Onlyavailablewhenpageisloadedandcreatedit.Youshouldcreateitateverytimewhenwannauseitagain.

    23

  • ServiceWorker:Persistent,installation,browser

    Daemonlikethingcanbeinstallonsystemakabrowser.

    Lifecycleisindependentfromwebpageorbrowser.ProvideversioncontrolforupdatefromsystemNicelyfitasentrypointtoRemoteNotification,BackgroundSync.andsoon.

    24

    file:///Applications/Marp.app/Contents/Resources/app.asar/slide.htmlfile:///Applications/Marp.app/Contents/Resources/app.asar/slide.html

  • REMINDER:

    Persistentbackgroundprocessingisagoalofserviceworker,anditdecidedallofserviceworkermechanism

    25

  • Whyeventdrivenmodel?

    PromisedeventsenablePersistentbackgroundprocessingevenifpageisn'tloading.Ithelpsofimplementingfeaturesthatneedsomethingmorethanpages.

    26

  • Spawn?No,install!

    spawnwouldbeexecutedatruntime.

    27

  • Lifecycle

    28

  • 2.1.1lifetime

    Thelifetimeofaserviceworkeristiedtotheexecutionlifetimeofevents,notreferencesheldbyserviceworkerclientstotheServiceWorkerobject.

    Theuseragentmayterminateserviceworkersatanytimeithasnoeventtohandleordetectsabnormaloperationsuchasinfiniteloopsandtasksexceedingimposedtimelimits,ifany,whilehandlingtheevents.

    29

    https://www.w3.org/TR/service-workers/#service-worker-lifetime

  • ServiceWorkerState

    enumServiceWorkerState{"installing","installed","activating","activated","redundant"};

    30

    https://www.w3.org/TR/service-workers/#service-worker-state

  • 31

  • SeviceWorkerfamilies

    32

  • OfflineCache

    Makeyourowndinosaurs!:p

    33

  • RemotePushNotification

    Alongtimeagoinagalaxyfar,faraway...therearespams

    34

  • BackgroundSync.

    Browserletyouknowperfecttimetoconnecttoserver.

    35

  • HTTPS

    ForavoidingmaninthemiddleattackHoweveryoucanuse127.0.0.1akalocalhostwithoutcertificatefortestingyourmodule.

    36

  • Showmethemoneycode!SimpleDemo:randomimageforsamerequest.:p

    37

    https://goo.gl/M3cucN

  • Pros.andCons.WhatdowehavetothinkaboutbeforeadoptingSW?

    38

  • There'snoPolyfills!

    Everythinghastwosides.

    Wedon'tneedtomanagepolyfillsandcheckourcodesrunwelloncrossbrowsingenvironments.:)Wedon'tusepolyfillforusingSWfeaturesonunsupportbrowsers.:/

    39

  • Adoptingitprogressively

    if('serviceWorker'innavigator){navigator.serviceWorker.register('/sw.js').then(function(registration){//registeredyourservicesdependonSW.:)if(enableServiceWorkerFeatures(registration)){//showsomehelpfulmessage.showSomeToastMessage();}});}

    40

  • Links[1/2]

    Specifications

    ServiceWorkerPushAPINotificationAPIFetchAPI

    Somearticles

    Offlinecookbook2016theyearofwebstreamsPushnotificationsontheopenWebWebPushEncryptionIsserviceworkerready?

    41

    https://slightlyoff.github.io/ServiceWorker/spec/service_worker/https://w3c.github.io/push-api/https://notifications.spec.whatwg.org/https://fetch.spec.whatwg.org/https://jakearchibald.com/2014/offline-cookbook/https://goo.gl/OmhuSwhttps://developers.google.com/web/updates/2015/03/push-notifications-on-the-open-webhttps://developers.google.com/web/updates/2016/03/web-push-encryption?hl=enhttps://jakearchibald.github.io/isserviceworkerready/

  • Links[2/2]

    Casestudies

    Productioncasestudies@developers.google.com

    Codes

    ServiceWorker101simpledemocodeSimplePushDemoby@gauntface

    Tools

    swprecacheswtoolbox

    42

    https://goo.gl/mgnwn7https://goo.gl/M3cucNhttps://gauntface.github.io/simple-push-demo/https://twitter.com/gauntfacehttps://github.com/googlechrome/sw-precachehttps://github.com/googlechrome/sw-toolbox

  • Thankyou!

    43