Alpha, Google Development Technologist (GDE)


GitHub Page and Markdown static blogs are very popular today. They are very suitable for technical thinking and habits. There are some excellent static blogging systems for different languages, such as Jekyll/Ruby, Pelican/Python, Hexo/NodeJs, because static content is very suitable for caching to speed up page access, uses Service worker to speed up page access. As a result, in addition to PageSpeed, CDN and other common server and network acceleration, Hexo/NodeJs achieves a better access experience through the client.



Speed up/offline access in just three steps

1. Add the registration code on the home page

   

2. Copy code

https://alphayang.github.io/sw.js saved to the root directory of your website.


3. Modify the cache domain name list and offline status page

Modify it in your sw.js


Open Chrome Dev Tools->Source to see which third-party sources your blog references and add them to the ignore list one by one.


Add offline. HTML to the root directory and use it when there is no network and no cache:


Add offline. SVG to the root directory and return it to image resource requests when there is no network.


4. Acceleration effect

After the home page is accelerated, the network request decreases from 16 to 1, the loading time decreases from 2.296s to 0.654s, and the instantaneous loading result is obtained.



Acceleration/off-line principle exploration

What is a Service worker?



As shown above, a Service worker is a browser-side proxy script written in Javascript that sits between your browser and the server. When a page registers a Service worker, it registers a set of event handlers to respond to events such as network requests and message pushes. The Service worker can be used to manage the cache and can be configured to return the cache or fetch from the network when responding to a network request. Since the Service worker is event-based, it is only called into memory when processing these events, without worrying that resident memory will slow the system down.


Service Worker life cycle


A Service worker adds a life cycle similar to that of an App to a Web page, which only responds to system events. Even when the browser is closed, the operating system can wake up the Service worker. This is very important, which makes the capabilities of Web App and Native App similar.


The Service worker triggers the Install event when registering, which can be used to pre-obtain and cache the resources required by the application and set the cache policy for each file.


Once the Service worker is activated, it can fully control the resources of the application, check network requests, modify network requests, retrieve and return content from the network, or return resources that have been previewed and cached by the installed Service worker. You can even generate content and return it to the network syntax.


All these users are transparent. In fact, a well-designed Service worker is like an intelligent cache system, which strengthens the network and cache functions, selects the optimal way to respond to network requests, and makes the application run more stably. It doesn’t matter if there is no network, because you can completely control the network response.


Control of the Service worker begins with the second page visit

When the page is first loaded, all resources are loaded from the network. The Service worker does not get a control network response when the page is first loaded, it only takes effect when the page is accessed later.


When the page is loaded for the first time, install is complete and the page enters idle state.



When the page is loaded for the second time, it enters the Activated state and is ready to process all events. At the same time, the browser sends an asynchronous request to the server to check whether the Service worker has a new version, which constitutes the update mechanism of the Service worker.


When the Service worker has processed all the events, it enters the idle state and ends up in terminated state. The resource is released and invoked again when a new event occurs.


The characteristics of

  • Browsers: Google Chrome, Firefox, Opera and various dual-core browsers in China are supported, but Safari is not, so the Service worker does not work in unsupported browsers.

  • HTTPS: Websites must enable HTTPS to ensure the security of pages using Service worker. Localhost is considered secure by default during development.

  • Non-block: the Javascript code in the Service worker must be non-blocking, because localStorage is obstructive, so it should not be used in the Service worker code.

  • Separate execution environment: Service workers run in their own global environment and usually in their own separate threads.

  • No binding to a specific page: The Service worker has control over the entire range of resources it loads.

  • DOM cannot be manipulated: the DOM is isolated from the environment in which it operates.


  • Can also run without browsing page: receive system events, background run.

  • Event-driven, run when needed, stop when not needed: execute on demand, load into memory only when needed.

  • Upgradeable: The latest version is asynchronously retrieved during execution.


Accelerate/go offline

Cache

There are many web caches, such as HTTP caches, localStorage, sessionStorage, and cacheStorage, which can be used in a flexible manner. However, it is too cumbersome to use the more advanced Service worker, which is the subject of this article.


Add the Service worker entry

Add the following code to the home page of your Web App


If the browser supports the Service worker, register it. If the browser does not support the Service worker, it will continue to browse without the enhancements provided by the Service worker.


Service worker control scope:

In a simple case, sw.js is placed in the root directory of the site so that the Service worker can control all pages of the site. Similarly, if sw.js is placed in /my-app/sw.js, it can only control pages in the my-app directory.

How about placing sw.js in /js/? What about better directory structure and scope control? Specify the JS location and set the scope at registration time.

navigator.serviceWorker.register(‘/js/sw.js’, {scope: ‘/sw-test/’}).then(function(registration) {

      // Registration was successful

      console.log(‘ServiceWorker registration successful with scope: ‘, registration.scope);

    }).catch(function(err) {

      // registration failed 🙁

      console.log(‘ServiceWorker registration failed: ‘, err);

    });


The Service worker implementation

Listen for three events:


install

   

All resources that meet the cache policy are cached when you install.


fetch


OnFetch serves as the proxy of the browser’s network request, and returns network or cache content as required. If the network content is obtained, the network request is returned and cached at the same time.

   

activate

///////////

// Activate

///////////

function onActivate(event) {

  log(‘activate event in progress.’);

  event.waitUntil(removeOldCache());

}

function removeOldCache() {

  return caches

    .keys()

    .then((keys) => {

      return Promise.all( // We return a promise that settles when all outdated caches are deleted.

        keys

         .filter((key) => {

return ! key.startsWith(version); // Filter by keys that don’t start with the latest version prefix.

         })

         .map((key) => {

           return caches.delete(key); // Return a promise that’s fulfilled when each outdated cache is deleted.

         })

      );

    })

    .then(() => {

      log(‘removeOldCache completed.’);

    });

}

 

Delete expired caches based on the version value at activate.


Management Service worker

Particular site

1) Google Chrome

Developer Tools – > Application – > Service Workers,


There are three more checkboxes here that are very useful:

  • Offline: simulates the Offline state

  • Update on reload: Updates during loading

  • Bypass for network: Always uses network content


2) Firefox

There is only an option in the Settings to use Service workers in an HTTP environment for debugging purposes, there is no Service worker management in a separate site.


3) Opera and other dual-core browsers as well as Google Chrome

If you see multiple Service workers in the same range, it indicates that the Service woker is updated and the original Service worker is not terminated.


Browser global

Take a look at what Service workers already exist in your browser.


1) Google Chrome

Type in the address bar:

chrome://serviceworker-internals/


As you can see, there are already 24 Service workers. You can either Start them manually or Unregister them.


2) Firefox

There are two ways to manually Start or unregister the Service worker interface.

  • Menu bar, Tool->Web Developer->Service Workers

  • Enter in the address bar:

    about:debugging#workers




3) Opera and other dual-core browsers as well as Google Chrome


More and more

TODO:

  • Updates to Service Workers need to be manually edited to version each time a new article is published;

  • Use AMP to maximize page rendering speed.


Other articles by author:

AR/VR/MR, what can Android developers do?

Android is everywhere, and there’s a lot Android developers can do

Take a tour of “I/O map development techniques” with Google development technologists