First knowledge of ServiceWorker

Source: Internet
Author: User

First knowledge of ServiceWorker
First knowledge of ServiceWorker

First knowledge of ServiceWorker

In March, W3C updated an API called Service Workers.

Those who have learned about Web Worker in HTML5 may be more familiar with this API, otherwise they will confuse the two APIs.

In fact, Service Worker is event-driven based on Web Worker. The mechanism they execute is to open a new thread to process some additional tasks that cannot be processed directly in the past. For Web Worker, we can use it for complex computing because it does not block rendering of the browser's main thread. The Service Worker can be used for local cache, which is equivalent to a local proxy. Speaking of caching, we will think of some of our frequently used caching technologies to cache our static resources. However, the old method does not support debugging and the flexibility is not high. Using Service Worker for caching, we can use javascript code to intercept http requests from the browser, set cached files, and return directly without going through the web server. Then, do more things you want to do.

Therefore, we can develop browser-based offline applications. This makes our web applications less dependent on the network. For example, we have developed a web application for news reading. When you use a mobile browser to enable it on the Internet, you can get news content normally. However, if the mobile phone enters the flight mode, you cannot use this application.

If we use the Service Worker for caching, the browser http request will first pass through the Service Worker and use url mapping for matching. If yes, the cached data will be used. If the matching fails, then you can continue to execute the specified action. In general, if a match fails, the page displays "the webpage cannot be opened ".

The above is the basic application scenario of Service Worker. Of course, it is not limited to data caching.

Here is a simple example:

/Index.html

12345678910111213141516
      
         <script>        // scope defaults to "/*"        navigator.serviceWorker.register("/service-worker.js").then(function(serviceWorker) {            console.log("success!");            // To use the serviceWorker immediately,            // you might call window.location.reload()        });    </script>      

Enter navigator. serviceWorker in the chrome console and you will find the returned undefined. This may be because your chrome version is earlier than 36, or you have not enabled this function. So first make sure that your chrome is upgraded to over 36. Go to chrome: // flags/and enable ServiceWorker, for example:
Vcmtlcg = ">
After completing the preceding two steps, you can view the returned values on the console:

In the above Code, register a file named service-worker.js for serviceWorker, the promise method used here. After the registration is successful, the callback function in then is executed.

Let's look at the service-worker.js.

1234567891011121314151617181920212223242526272829303132333435363738
this.oninstall = function(e) {    // Create a cache of resources.    var resources = new Cache();    var visited = new Cache();    // Fetch them.    e.waitUntil(resources.add(        "/index.html",        "/fallback.html",        "/css/base.css",        "/js/app.js",        "/img/logo.png"    ).then(function() {        // Add caches to the global caches.        return Promise.all([            caches.set("v1", resources),            caches.set("visited", visited)        ]);    }));}; this.onfetch = function(e) {    e.respondWith(        // Check to see if request is found in cache        caches.match(e.request).catch(function() {            // It's not? Prime the cache and return the response.            return caches.get("visited").then(function(visited) {                return fetch(e.request).then(function(response) {                    visited.put(e.request, response);                    // Don't bother waiting, respond already.                    return response;                });            });        }).catch(function() {            // Connection is down? Simply fallback to a pre-cached page.            return caches.match("/fallback.html");        });    );};

Oninstall: run when the worker is loaded

In the oninstall callback function, some static files to be cached are written to the global cache object.

Onfetch: executed when a user's request is received

Through e. request matches the static file in the cache. If yes, the cached file is returned. If no match is found, the file is caught and the request is released (to request the Real Server ), and cache the new file to the global cache. Promise is also used here.

In my opinion, using ServiceWorker for caching is equivalent to a proxy that can intercept http requests so that you can customize the requests. Even if there is no network, ServiceWorker can be used as an http server to return the data required by the front-end.

The above is my reference and understanding of ServiceWorker. At present, there are still few Chinese and English documents, mainly including W3C introduction.

References:
Simple ServiceWorker example

Code on Github

W3C ServiceWorkers

Author: foreverpx
Link to the original article: ServiceWorker

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.