Service Worker

 

1. Service Worker Identity

Service means service, Worker means workers, the Service Worker, which means that staff. The staff is June 2014 HTML5 new tactics interns, currently in trial. Prior to this, there have been an old employee, it is called Web Worker. So the question is, who Boss yes? Boss is the browser. Precisely, javascript running the main thread of each page is a Boss.

Here to talk about the large background. Boss is very powerful to guide the country on the page, anything they want. But he has a limitation: only one thing at a time (single-threaded). When some very time-consuming chores allow Boss to deal with in the course of treatment he would attend to other important things. From a user perspective, nobody page, Boss is not the Director-General! Boss is very depressed at this time. In order to ensure Boss can handle more important things, the Board of Directors (W3C) has finally recruited a new employee: Web worker. This time, Boss finally freed from the time-consuming chores, he need only Web worker called me and said: "These things take to do, did not finish do not come to me." Web worker received after the task quietly to their station (threads) to work and sent a message after the completion of (postMessage) to the Boss. After Boss received the message (onmessage) pleased nod.

Pulled a long time about the new staff seems not ah. . . Do not worry, here we're talked about.

Boss off work (page closed), Web worker also pack up and go home. Such execution for a long time, until June 2014, the board found a problem: "Nobody actually work overtime after the boss from work?." So, they recruit a full-time overtime: Service Worker. Performance targets it is given as follows:

  1. After the entry (install) never to work, and can be updated.
  2. We can handle the resource (HTTPS request) Boss needs to be taken to make BOSS data line (from the cache).
  3. Can push messages to the client ( the Push. Notifications The )
  4. Matter (DOM ACCESS) does not allow unauthorized management of Boss

Generally speaking, Service worker is independent of the page a runtime environment, it can still run after the page is closed. At the same time, it can be intercepted and return request (Fiddler like) it is responsible for network requests a page.

2. Conditions of Use

  • Conditions request protocol HTTPS. After all, the right to a larger Service Worker, you can directly intercept and return the user's request, for security reasons so the current can only use the Service Worker in HTTPS environment.
  • Browser support
     small currently supported browsers, and browsers are also supported in the pilot phase.

    3. a chestnut

    The following example shows how to implement a page off-line by Service Worker, after the first visit, follow-up even without a network connection, but also the resources necessary to get the page from cache. Examples of one derived from GitHub Demo .
  • Code page file:
<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Service Worker offline demo</title>
    <style>
        body {
            background-image: url("./images/background.jpeg");/*背景图片*/
        }
    </style>
</head>
<body>

<div>Learn Web Design &amp; Development with SitePoint tutorials, 
Books and courses - HTML5, CSS3, JavaScript, PHP, Mobile App Development, Responsive Web Design </ div > 
< Script > 
    IF (navigator.serviceWorker) {
         // Register Service Worker scope shows the effect of a page path 
        // the Register function returns Promise 
        navigator.serviceWorker.register ( ' ./service-worker.js ' , {scope: ' ./ ' })
            .then(function (registration) {
                console.log(registration);
            })
            .catch(function (e) {
                console.error(e);
            })
    } else {
        console.log('Service Worker is not supported in this browser.')
    }
</script>
</body>
</html>
  • Service Worker文件:service-worker.js
importScripts ( 'JS / Cache-polyfill.js'); // Cache extension

var CACHE_VERSION = 'App-V1'; // version of the cache file 
var CACHE_FILES = [ // needs to be cached page file 
    '/' ,
     'Images / background.jpeg' ,
     'JS / app.js' ,
     ' CSS / Styles .css'
];


self.addEventListener ( 'install', function (Event) { // listen install event worker's 
    event.waitUntil ( // delay install the event until the cache initialization is complete 
        caches.open (CACHE_VERSION)
            .then(function (cache) {
                console.log('Opened cache');
                return cache.addAll(CACHE_FILES);
            })
    );
});

self.addEventListener ( 'activate', function (Event) { // listen activate event worker's 
    event.waitUntil ( // delay activate event until 
        caches.keys (). the then ( function (Keys) {
             return Promise.all (Keys. the Map ( function (Key, i) { // clear the cache old versions 
                IF (Key ==! CACHE_VERSION) {
                     return caches. the Delete (Keys [i]);
                }
            }))
        })
    )
});

self.addEventListener ( 'FETCH', function (Event) { // taken resources requested page 
    event.respondWith ( // returns the resource requested page 
        caches.match (event.request) .then ( function (RES) { // Analyzing whether a cache hit 
            iF (RES) {   // returns a resource cache 
                return RES;
            }
            requestBackend (Event); // perform backup operations requesting 
        })
    )
});

function requestBackend (Event) {   // request backup 
    var URL = event.request.clone ();
     return FETCH (URL) .then ( function (RES) { // request online resources 
        // IF A Not Valid The Send Response error 
        IF (RES || || res.type 200 is res.status == == 'Basic'!!! ) {
             return RES;
        }

        var response = res.clone();

        caches.open (CACHE_VERSION) .then ( function (Cache) { // cache resources obtained from the line 
            cache.put (event.request, response);
        });

        return res;
    })
}

 

  • Lifecycle Service Worker

    Service Worder after installation (install) and activated (activate), will enter the normal working condition. When it is responsible for the page is opened in a browser, it will process the request page. In other cases (except under special circumstances: service worker will be updated regularly), Service worker process suspended, will not take up memory and CPU resources.

  • Examples of operating results



    on a graph after the first page is opened, closed network, a request to open a page again. Page still open in offline, and can get to the appropriate style and script resources. As can be seen from the figure, access to resources is the way "from ServiceWorker", explained indeed serviceWorker in working.

4. Turn chrome hidden skills

There are three debug-related service Worker and viewing tools on chrome

  • serivce worker 1 watch is running: chrome: // inspect / # service-workers
  • 2 ervice Worker debugging (see console.log output can also be written off worker)
  •  
  • Resources 3 Tibetan viewing options open as follows:

    1 enter chrome: // flags turned on 'the Enable DevTools Experiments'.
    2 Open DevTools, enter Setting> Experiments, continuously press the shift key 6 under
    3 will be able to see just open hidden features in DevTools the Resources pages:

5. Summary

Service Worker is the second web Worker after a new thread, which separate more thorough than web worker, you can not open the page when it is running. As an intermediate layer between a page and a server, Service Worker can capture request it is responsible for the page, and returns the corresponding resources, which make offline web applications become possible. This is also an important objective of Service Worker been raised. Although supported browsers and platforms are not many, but still in the experimental stage, but has been developed W3C specification . In the future, when more mature and Service Worker universal time, it will open new doors for the web app.

 

Transfer: https://www.imweb.io/topic/56592b8a823633e31839fc01

Guess you like

Origin www.cnblogs.com/fangsmile/p/12061393.html