banner



What Does Register Service Worker Do

This chapter is from the book

Registering a Service Worker

Spider web apps follow a specific process to install a service worker; in that location'southward no automatic way to do it today. The app basically executes some JavaScript code to register the service worker with the browser. In the Tip Calculator app in Chapter 1, "Introducing Progressive Web Apps," I added the code to do this straight in the app's index.html file. For the PWA News app, we use a different approach.

In this section, you'll modify the project'south existing public/index.html file plus add 2 JavaScript files: public/js/sw-reg.js and public/sw.js.

In the <caput> department of the project'due south public/index.html file, add the following lawmaking:

          <!-- Annals the service worker --> <script src='js/sw-reg.js'></script>        

This tells the web app to load a JavaScript file that registers the service worker for us. Next, let's create that file. Create a new file called public/js/sw-reg.js and populate the file with the lawmaking shown in Listing 3.2.

Listing 3.2 PWA News sw-reg.js File

          // does the browser support service workers? if ('serviceWorker' in navigator) {   // and then register our service worker   navigator.serviceWorker.register('/sw.js')     .and then(reg => {       // display a success message       console.log(`Service Worker Registration (Telescopic: ${reg.scope})`);     })     .catch(error => {       // display an fault message       let msg = `Service Worker Fault (${error})`;       panel.error(msg);       // brandish a warning dialog (using Sweet Alert 2)       Swal.fire('', msg, 'mistake');     }); } else {   // happens when the app isn't served over a TLS connection (HTTPS)   // or if the browser doesn't back up service workers   console.warn('Service Worker non available'); }        

The lawmaking hither isn't very complicated; it all centers around the phone call to navigator.serviceWorker.register. The code beginning checks to meet if the serviceWorker object exists in the browser'southward navigator object. If it does, and then this browser supports service workers. Subsequently the code verifies it tin register the service worker, information technology does so through the telephone call to navigator.serviceWorker.register.

The register method returns a promise, and so the code includes then and catch methods to act depending on whether the installation succeeded or failed. If it succeeds, it tosses a elementary message out to the panel. If the call to register fails (caught with the catch method), we warn the user with an alert dialog.

Ii potential fault conditions exist here: if the browser doesn't back up service workers and if service worker registration fails. When the browser doesn't back up service workers, I log a simple alert to the console (using panel.warn). I don't do anything special to warn the user because this is progressive enhancement, correct? If the browser doesn't support service workers, the user just continues to use the app as is, with no special capabilities provided through service workers.

On the other mitt, if registration fails, so the lawmaking is broken (considering we already know the browser supports service workers), and I desire to allow you know more obnoxiously with an warning dialog. I did this because you're learning how this works, and I wanted the fault condition to be easily recognized. I probably wouldn't do this for production apps because if the service worker doesn't register, the app simply falls back to the normal way of operation.

Service workers don't start working until the next page loads anyway, so to go along things clean, you can defer registering the service worker until the app finishes loading, as shown in Listing 3.3.

Listing 3.3 PWA News sw-reg.js File (Alternate Version)

          // does the browser support service workers? if ('serviceWorker' in navigator) {   // Defer service worker installation until the page completes loading   window.addEventListener('load', () => {     // then register our service worker     navigator.serviceWorker.register('/sw.js')       .and then(reg => {         // display a success bulletin         console.log(`Service Worker Registration (Telescopic: ${reg.scope})`);       })       .catch(error) => {         // display an error message         allow msg = `Service Worker Fault (${error})`;         console.error(msg);         // brandish a warning dialog (using Sweet Alarm 2)         Swal.fire('', msg, 'fault');       });   }) } else {     // happens when the app isn't served over a TLS connection (HTTPS)     // or if the browser doesn't support service workers     console.warn('Service Worker not bachelor'); }        

In this case, the code adds an event listener for the load issue and starts service worker registration after that event fires. All this does is defer the boosted work until the app is done with all its other startup stuff and shouldn't even be noticeable to the user.

Next, let'due south create a service worker. Create a new file called public/sw.js and populate it with the lawmaking shown in Listing iii.4. Find that we created the service worker registration file in the project's public/js/ folder, but this one goes into the web app'south root folder (public/); I'll explain why in "Service Worker Telescopic" later in this chapter—I'm just mentioning it now to save you a potential problem later if you put it in the wrong place.

Listing 3.four Outset Service Worker Example: sw-34.js

          self.addEventListener('fetch', outcome => {   // fires whenever the app requests a resource (file or information)   console.log(`SW: Fetching ${event.request.url}`); });        

This code is unproblematic likewise. All it does is create an event listener for the browser'southward fetch consequence, then logs the requested resource to the console. The fetch event fires whenever the browser, or an app running in the browser, requests an external resource (such as a file or data). This is different from the JavaScript fetch method, which enables an app'due south JavaScript code to request data or resources from the network. The browser requesting resources (such as a JavaScript or epitome file referenced in an HTML script or img tag) and a spider web app'due south JavaScript code requesting a resource using the fetch method volition both cause the fetch effect to burn down.

This is the core functionality of a service worker, intercepting fetch events and doing something with the asking—such as getting the requested resource from the network, pulling the requested file from cache, or even sending something completely different to the app requesting the resource. It's all upward to you: your service worker delivers as much or equally piffling enhancement equally needed for your app.

With this file in place, refresh the app in the browser and watch what happens. Nothing, correct? There'southward not much to meet hither since, everything happens under the covers. In this case, the service worker does cipher except log the consequence; as y'all tin can see in the browser, the app loaded as expected, so the app'due south notwithstanding working the same equally it did before.

Open the browser's programmer tools and look for a tab labeled Application (or something similar) and a side tab labeled Service Workers. If yous did everything correct, you should run into your service worker properly registered in the browser, every bit shown in Figure 3.5 (in Google Chrome).

If the browser tin can't register the service worker, information technology displays fault messages in this panel to let y'all know.

In the latest Chrome browser and the Chromium-based Edge browser, you tin can likewise open up a special page that displays information about all service workers registered in the browser. Open the browser and enter the following value in the address bar:

          chrome://serviceworker-internals/        

The browser opens the page shown in Figure 3.6, listing all registered service workers.

The i thing missing from the service worker as it stands today is for it to really practice something with the fetch request. List three.v adds an boosted line of code to our existing service worker:

          event.respondWith(fetch(issue.request));        

This lawmaking instructs the browser to go ahead and get the requested file from the network. Without this statement in the upshot listener, the browser was doing this anyway. Since the event listener didn't act on the request and return a promise telling the browser information technology was dealing with it, then the browser goes ahead and gets the file anyway. That's why the app works without this line. Calculation the line just completes the event listener.

List three.5 2d Service Worker Instance: sw-35.js

          self.addEventListener('fetch', upshot => {   // fires whenever the app requests a resource (file or data)   console.log(`SW: Fetching ${event.asking.url}`);   // side by side, go get the requested resource from the network,   // nothing fancy going on here.   upshot.respondWith(fetch(issue.request)); });        

The browser passes the fetch event listener an event object service workers query to determine which resources was requested. Service workers utilize this mechanism to determine whether to get the resources from cache or asking it from the network. I encompass this in more than particular later (in this chapter and the next), simply for now this extra line of lawmaking only enforces what we've already seen the browser practise—get the requested resource from the network.

The browser fires two other events of interest to the service worker programmer: install and activate. Listing three.6 shows a service worker with event listeners for both included.

Listing 3.6 Third Service Worker Example: sw-36.js

          self.addEventListener('install', event => {   // fires when the browser installs the app   // here we're just logging the event and the contents   // of the object passed to the issue. the purpose of this event   // is to requite the service worker a identify to setup the local   // environment after the installation completes.   console.log(`SW: Event fired: ${event.blazon}`);   panel.dir(event); });  self.addEventListener('activate', event => {   // fires afterward the service worker completes its installation.   // It's a place for the service worker to clean up from   // previous service worker versions.   console.log(`SW: Upshot fired: ${outcome.type}`);   console.dir(event); });  cocky.addEventListener('fetch', event => {   // fires whenever the app requests a resources (file or information)   console.log(`SW: Fetching ${event.asking.url}`);   // next, go get the requested resources from the network,   // nothing fancy going on here.   consequence.respondWith(fetch(consequence.request)); });        

The browser fires the install event when it completes installation of the service worker. The event provides the app with an opportunity to practise the setup work required by the service worker. At this betoken, the service worker is installed simply non even so operational (it doesn't do anything yet).

The browser fires the activate event when the current service worker becomes the agile service worker for the app. A service worker works at the browser level, not the app level, so when the browser installs it, it doesn't get active until the app reloads in all browser tabs running the app. One time it activates, information technology stays agile for any browser tabs running the app until the browser closes all tabs for the app or the browser restarts.

The activate event provides service workers with an opportunity to perform tasks when the service worker becomes the agile service worker. Usually, this means cleaning up any buried data from a previous version of the app (or service worker). You'll learn a lot more than about this in Chapter 4, "Resources Caching"; for at present, let's add this code to our existing service worker and run across what happens.

In one case y'all've updated the code, reload the folio in the browser, then open the developer tools console panel and look for the output shown in Figure 3.7. Chances are, you lot won't meet it—that'south considering the previous version of the service worker is all the same agile. You lot should see the install upshot burn down but not the actuate event.

FIGURE 3.7

Figure 3.7 Chrome Browser Tools Console Pane with Installation Output

You have several options for activating this new service worker. I explain two here and cover programmatic options in "The Service Worker Lifecycle" later on in the chapter. One selection is to close and reopen the browser, then reload the app; this automatically enables the registered service worker.

Another option is to configure the browser developer tools to automatically activate the new service worker one time information technology registers the service worker; this approach is useful only when debugging or testing a PWA. At the meridian of the service workers pane shown in Figure 3.five is a checkbox labeled Update on reload; when you enable (bank check) this checkbox, the browser automatically updates and activates new service workers every time you reload the page with a new service worker.

Force the browser to activate the new service worker, and so expect at the panel page. You should now see the output shown in Figure 3.8 with each network asking logged to the panel.

FIGURE 3.8

Effigy 3.8 Chrome Browser Tools Console Pane with Service Worker Output

At this bespeak, the app has a functioning service worker listening for all relevant events and fetching all requested resources from the network. In the side by side sections, nosotros talk about service worker scope (every bit promised) and the service worker lifecycle; and then I'll evidence you more you can do with service workers.

What Does Register Service Worker Do,

Source: https://www.informit.com/articles/article.aspx?p=2999382&seqNum=4

Posted by: gorebuttp1999.blogspot.com

0 Response to "What Does Register Service Worker Do"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel