banner



Do You Need To Register Your Service Dog

The service worker lifecycle

— Updated

The lifecycle of the service worker is its most complicated part. If you don't know what it's trying to practice and what the benefits are, it can feel like it'south fighting you. But one time you know how information technology works, you can evangelize seamless, unobtrusive updates to users, mixing the best of web and native patterns.

This is a deep dive, but the bullets at the kickoff of each section cover almost of what y'all need to know.

The intent #

The intent of the lifecycle is to:

  • Brand offline-showtime possible.
  • Let a new service worker to get itself ready without disrupting the current 1.
  • Ensure an in-scope page is controlled by the same service worker (or no service worker) throughout.
  • Ensure there's merely one version of your site running at in one case.

That terminal 1 is pretty important. Without service workers, users can load one tab to your site, and then later open another. This tin consequence in two versions of your site running at the same time. Sometimes this is ok, but if you're dealing with storage you tin easily end up with two tabs having very different opinions on how their shared storage should be managed. This can result in errors, or worse, data loss.

The first service worker #

In brief:

  • The install event is the showtime effect a service worker gets, and it merely happens once.
  • A promise passed to installEvent.waitUntil() signals the duration and success or failure of your install.
  • A service worker won't receive events similar fetch and push until it successfully finishes installing and becomes "active".
  • Past default, a page'south fetches won't go through a service worker unless the folio asking itself went through a service worker. So you'll need to refresh the folio to see the effects of the service worker.
  • clients.claim() can override this default, and take control of not-controlled pages.

Have this HTML:

                                          <!                DOCTYPE                html                >                            
An epitome volition appear here in three seconds:
<script >
navigator.serviceWorker. register ( '/sw.js' )
. so ( reg => console. log ( 'SW registered!' , reg) )
. catch ( err => console. log ( 'Boo!' , err) ) ;

setTimeout ( ( ) => {
const img = new Image ( ) ;
img.src = '/dog.svg' ;
certificate.body. appendChild (img) ;
} , 3000 ) ;

</script >

It registers a service worker, and adds image of a canis familiaris afterwards 3 seconds.

Here'due south its service worker, sw.js:

            self.              addEventListener              (              'install'              ,              effect              =>              {              
console. log ( 'V1 installing…' ) ;

// cache a cat SVG
outcome. waitUntil (
caches. open ( 'static-v1' ) . then ( cache => enshroud. add ( '/cat.svg' ) )
) ;
} ) ;

self. addEventListener ( 'activate' , issue => {
console. log ( 'V1 now ready to handle fetches!' ) ;
} ) ;

self. addEventListener ( 'fetch' , event => {
const url = new URL (event.request.url) ;

// serve the cat SVG from the cache if the request is
// same-origin and the path is '/dog.svg'
if (url.origin == location.origin && url.pathname == '/dog.svg' ) {
event. respondWith (caches. match ( '/cat.svg' ) ) ;
}
} ) ;

It caches an image of a true cat, and serves it whenever in that location's a request for /dog.svg. However, if you run the above example, you'll run across a canis familiaris the start time you load the folio. Hit refresh, and you'll encounter the true cat.

Note: Cats are meliorate than dogs. They just are.

Scope and command #

The default telescopic of a service worker registration is ./ relative to the script URL. This means if you annals a service worker at //instance.com/foo/bar.js it has a default scope of //instance.com/foo/.

We call pages, workers, and shared workers clients. Your service worker can only control clients that are in-scope. Once a client is "controlled", its fetches go through the in-scope service worker. You can detect if a customer is controlled via navigator.serviceWorker.controller which will be zip or a service worker instance.

Download, parse, and execute #

Your very starting time service worker downloads when you call .register(). If your script fails to download, parse, or throws an error in its initial execution, the register hope rejects, and the service worker is discarded.

Chrome's DevTools shows the mistake in the console, and in the service worker department of the application tab:

Error displayed in service worker DevTools tab

Install #

The showtime issue a service worker gets is install. It'south triggered as soon as the worker executes, and information technology'southward only called in one case per service worker. If you lot modify your service worker script the browser considers information technology a dissimilar service worker, and information technology'll get its own install event. I'll cover updates in detail later on.

The install issue is your chance to cache everything you demand before being able to control clients. The hope you laissez passer to event.waitUntil() lets the browser know when your install completes, and if it was successful.

If your promise rejects, this signals the install failed, and the browser throws the service worker away. It'll never control clients. This means we can't rely on cat.svg being present in the cache in our fetch events. It's a dependency.

Activate #

Once your service worker is ready to control clients and handle functional events like push and sync, y'all'll go an activate result. But that doesn't mean the page that called .register() will exist controlled.

The first time you lot load the demo, even though dog.svg is requested long after the service worker activates, it doesn't handle the asking, and you still see the prototype of the canis familiaris. The default is consistency, if your page loads without a service worker, neither will its subresources. If you load the demo a 2nd time (in other words, refresh the page), it'll be controlled. Both the page and the image will go through fetch events, and y'all'll see a cat instead.

clients.claim #

Yous can take control of uncontrolled clients by calling clients.claim() within your service worker one time it'due south activated.

Here's a variation of the demo above which calls clients.claim() in its activate event. You should see a cat the first time. I say "should", because this is timing sensitive. You'll simply see a cat if the service worker activates and clients.claim() takes result earlier the image tries to load.

If you lot use your service worker to load pages differently than they'd load via the network, clients.claim() tin can exist troublesome, equally your service worker ends upwards decision-making some clients that loaded without it.

Updating the service worker #

In brief:

  • An update is triggered if whatsoever of the post-obit happens:
    • A navigation to an in-scope page.
    • A functional events such as push and sync, unless at that place'southward been an update check within the previous 24 hours.
    • Calling .register() only if the service worker URL has inverse. Yet, you lot should avoid changing the worker URL.
  • Most browsers, including Chrome 68 and afterward, default to ignoring caching headers when checking for updates of the registered service worker script. They still respect caching headers when fetching resources loaded inside a service worker via importScripts(). You tin can override this default beliefs by setting the updateViaCache option when registering your service worker.
  • Your service worker is considered updated if it's byte-different to the one the browser already has. (We're extending this to include imported scripts/modules likewise.)
  • The updated service worker is launched alongside the existing ane, and gets its own install outcome.
  • If your new worker has a not-ok status code (for instance, 404), fails to parse, throws an error during execution, or rejects during install, the new worker is thrown abroad, simply the electric current one remains active.
  • Once successfully installed, the updated worker will wait until the existing worker is controlling zero clients. (Note that clients overlap during a refresh.)
  • cocky.skipWaiting() prevents the waiting, meaning the service worker activates equally soon every bit it's finished installing.

Let's say nosotros changed our service worker script to respond with a picture of a horse rather than a cat:

                          const              expectedCaches              =              [              'static-v2'              ]              ;              

self. addEventListener ( 'install' , event => {
console. log ( 'V2 installing…' ) ;

// cache a horse SVG into a new cache, static-v2
consequence. waitUntil (
caches. open ( 'static-v2' ) . then ( cache => enshroud. add ( '/equus caballus.svg' ) )
) ;
} ) ;

self. addEventListener ( 'activate' , event => {
// delete any caches that aren't in expectedCaches
// which volition become rid of static-v1
result. waitUntil (
caches. keys ( ) . and so ( keys => Promise. all (
keys. map ( central => {
if ( !expectedCaches. includes (fundamental) ) {
return caches. delete (key) ;
}
} )
) ) . and so ( ( ) => {
console. log ( 'V2 now ready to handle fetches!' ) ;
} )
) ;
} ) ;

self. addEventListener ( 'fetch' , event => {
const url = new URL (event.request.url) ;

// serve the horse SVG from the cache if the request is
// same-origin and the path is '/domestic dog.svg'
if (url.origin == location.origin && url.pathname == '/dog.svg' ) {
event. respondWith (caches. match ( '/horse.svg' ) ) ;
}
} ) ;

Check out a demo of the above. You should withal see an image of a cat. Here'southward why…

Install #

Note that I've inverse the cache proper name from static-v1 to static-v2. This means I can ready the new enshroud without overwriting things in the current i, which the old service worker is still using.

This patterns creates version-specific caches, akin to assets a native app would bundle with its executable. Y'all may also have caches that aren't version specific, such equally avatars.

Waiting #

After it's successfully installed, the updated service worker delays activating until the existing service worker is no longer controlling clients. This country is chosen "waiting", and information technology'south how the browser ensures that merely 1 version of your service worker is running at a time.

If you ran the updated demo, you should still see a picture of a cat, because the V2 worker hasn't withal activated. You tin can run across the new service worker waiting in the "Application" tab of DevTools:

DevTools showing new service worker waiting

Even if you only take 1 tab open to the demo, refreshing the page isn't enough to let the new version take over. This is due to how browser navigations piece of work. When you lot navigate, the electric current page doesn't go away until the response headers accept been received, and even then the electric current page may stay if the response has a Content-Disposition header. Because of this overlap, the electric current service worker is always controlling a client during a refresh.

To get the update, shut or navigate away from all tabs using the current service worker. And then, when you navigate to the demo again, yous should see the horse.

This pattern is similar to how Chrome updates. Updates to Chrome download in the groundwork, but don't employ until Chrome restarts. In the mean time, you tin can continue to apply the current version without disruption. Nonetheless, this is a hurting during development, but DevTools has ways to get in easier, which I'll cover later in this article.

Activate #

This fires once the old service worker is gone, and your new service worker is able to control clients. This is the ideal time to do stuff that you couldn't do while the old worker was still in use, such every bit migrating databases and clearing caches.

In the demo in a higher place, I maintain a list of caches that I await to exist in that location, and in the activate consequence I go rid of any others, which removes the onetime static-v1 enshroud.

If y'all pass a promise to event.waitUntil() it'll buffer functional events (fetch, push, sync etc.) until the hope resolves. So when your fetch event fires, the activation is fully complete.

Skip the waiting phase #

The waiting phase means you're only running i version of your site at in one case, but if you don't need that feature, you can make your new service worker actuate sooner past calling self.skipWaiting().

This causes your service worker to kick out the current active worker and activate itself as before long as it enters the waiting stage (or immediately if it's already in the waiting stage). It doesn't crusade your worker to skip installing, but waiting.

It doesn't really matter when yous telephone call skipWaiting(), as long as it'south during or earlier waiting. It's pretty common to call information technology in the install effect:

            self.              addEventListener              (              'install'              ,              event              =>              {              
cocky. skipWaiting ( ) ;

event. waitUntil (
// caching etc
) ;
} ) ;

But you may want to call it every bit a results of a postMessage() to the service worker. Every bit in, you want to skipWaiting() following a user interaction.

Here'southward a demo that uses skipWaiting(). Y'all should run across a picture of a cow without having to navigate abroad. Like clients.merits() it'southward a race, so you'll merely see the cow if the new service worker fetches, installs and activates earlier the page tries to load the prototype.

Manual updates #

As I mentioned before, the browser checks for updates automatically after navigations and functional events, only you can likewise trigger them manually:

            navigator.serviceWorker.              register              (              '/sw.js'              )              .              then              (              reg              =>              {              
// sometime later on…
reg. update ( ) ;
} ) ;

If you expect the user to be using your site for a long time without reloading, you may desire to call update() on an interval (such equally hourly).

Avoid changing the URL of your service worker script #

If you lot've read my mail on caching all-time practices, you may consider giving each version of your service worker a unique URL. Don't practise this! This is usually bad practice for service workers, only update the script at its electric current location.

It can land you with a trouble like this:

  1. alphabetize.html registers sw-v1.js as a service worker.
  2. sw-v1.js caches and serves index.html so it works offline-first.
  3. Y'all update alphabetize.html and then it registers your new and shiny sw-v2.js.

If yous practice the above, the user never gets sw-v2.js, because sw-v1.js is serving the sometime version of alphabetize.html from its cache. You lot've put yourself in a position where yous need to update your service worker in society to update your service worker. Ew.

However, for the demo to a higher place, I have inverse the URL of the service worker. This is so, for the sake of the demo, you can switch between the versions. It isn't something I'd do in production.

The service worker lifecycle is built with the user in mind, merely during development it's a flake of a pain. Thankfully at that place are a few tools to help out:

Update on reload #

This one's my favourite.

DevTools showing 'update on reload'

This changes the lifecycle to exist developer-friendly. Each navigation will:

  1. Refetch the service worker.
  2. Install it as a new version even if it's byte-identical, meaning your install event runs and your caches update.
  3. Skip the waiting phase so the new service worker activates.
  4. Navigate the folio.

This ways you'll go your updates on each navigation (including refresh) without having to reload twice or close the tab.

Skip waiting #

DevTools showing 'skip waiting'

If y'all have a worker waiting, you tin can hitting "skip waiting" in DevTools to immediately promote it to "active".

Shift-reload #

If you force-reload the folio (shift-reload) it bypasses the service worker entirely. It'll be uncontrolled. This feature is in the spec, so it works in other service-worker-supporting browsers.

Handling updates #

The service worker was designed every bit office of the extensible web. The idea is that we, as browser developers, acknowledge that we are non improve at web evolution than web developers. And as such, we shouldn't provide narrow high-level APIs that solve a particular problem using patterns we like, and instead give you lot access to the guts of the browser and let you exercise information technology how y'all want, in a fashion that works best for your users.

And then, to enable every bit many patterns as we tin can, the whole update wheel is appreciable:

            navigator.serviceWorker.              register              (              '/sw.js'              )              .              so              (              reg              =>              {              
reg.installing; // the installing worker, or undefined
reg.waiting; // the waiting worker, or undefined
reg.active; // the agile worker, or undefined

reg. addEventListener ( 'updatefound' , ( ) => {
// A wild service worker has appeared in reg.installing!
const newWorker = reg.installing;

newWorker.country;
// "installing" - the install outcome has fired, but non yet consummate
// "installed" - install complete
// "activating" - the activate event has fired, merely not yet complete
// "activated" - fully active
// "redundant" - discarded. Either failed install, or it'southward been
// replaced by a newer version

newWorker. addEventListener ( 'statechange' , ( ) => {
// newWorker.state has inverse
} ) ;
} ) ;
} ) ;

navigator.serviceWorker. addEventListener ( 'controllerchange' , ( ) => {
// This fires when the service worker controlling this folio
// changes, eg a new worker has skipped waiting and become
// the new active worker.
} ) ;

The lifecycle goes ever on #

Equally you tin can see, it pays to understand the service worker lifecycle—and with that agreement, service worker behaviors should seem more logical, and less mysterious. That noesis volition give you more conviction equally yous deploy and update service workers.

Last updated: — Improve article

Return to all manufactures

Source: https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle

Posted by: blatttheessale.blogspot.com

0 Response to "Do You Need To Register Your Service Dog"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel