Html5-service worker implements offline page access __html

Source: Internet
Author: User

If you mention HTML5 's new api,websocket, WEB workers should be more familiar. WebSocket is a new protocol for outlining the number of requests, and WEB workers is used to implement the multithreading of browsers. The service worker to be introduced today is for the offline caching of pages, providing services like app. Note that this is not the same as browser caching.

All the following code please view GitHub download full version 1. Service Worker Introduction

Just imagine, when you are visiting a person's blog directory, when you find the blog you are interested in, you want to click into the full blog, this time the network is broken, you will see the following page:

Ignoring the URL above, this is the result of using the Chrome-> developer tool in my own browser-> New Work-> offline to simulate a disconnected network and access the Web page on my local server. You see the page should be similar. It is not possible to solve the problem by simply relying on browser caching. So HTML5 the Service Worker, a script that runs in the background of the browser, independent of the current page, and provides the ability to silently implement the Web page's functionality without interacting with it. In the future, services such as message push, silent updates, and geo-fencing can be implemented, but at the moment it is the first function to intercept and process network requests, including programmable response cache management. Therefore, it can be used to break the network easily achieve interception of user requests, with the cached page instead of server response, referred to as offline caching.
Note: Service worker only supports HTTPS protocol or localhost because of high privilege 2. Service worker uses 2.1 life cycle

Let's take a look at a service worker's cycle (Photo source: http://www.html5rocks.com/en/tutorials/service-worker/introduction/)

Service worker has a life cycle that is completely independent of the Web page.

To get a service worker to take effect on your site, you need to register it with your Web page first. After registering for a service worker, the browser silently initiates a service worker installation process in the background.

During the installation process, the browser loads and caches some static resources. If all the files are cached successfully, the service worker is installed successfully. If any file loading or caching fails, the installation process fails, and service worker cannot be activated (i.e. failed to install successfully). If this happens, don't worry, it will try the installation again the next time.

When the installation is complete, the next step for service worker is to activate, at which point you can also upgrade a service worker version, which we'll talk about later.

After activation, service worker will take over all pages within its jurisdiction, but if a page is just registered for service worker, it will not be taken over this time, and the service worker will not take effect until the next time the page loads.

When a service worker takes over a page, it may have two states: it is either terminated to conserve memory, or it handles the fetch and message events, either in the presence of a network request or on a page.

To sum up, there are several key steps in the life cycle of the service worker (that is, events that often require listening and setting up callback functions):
1. Installation
2. Activate, after successful activation, open chrome://inspect/#service-workers can view the currently running service worker
3. Listening for the fetch and message events, the following two events are briefly described
4. Destruction, destruction by the browser, if a service worker is not used for a long time or the machine memory is limited, it may destroy this worker
The following is a detailed description of these events. 2.2 Several events that are often monitored during the lifecycle Fetch Event

When the page initiates an HTTP request, the service worker can intercept the request by the fetch event and give its own response.
The consortium provides a new fetch API to replace XMLHttpRequest, with a maximum difference of two points with XMLHttpRequest:

The fetch () method returns the Promise object, which is called continuously by the then method to reduce nesting. ES6 's promise will become more and more convenient to developers after becoming a standard.

Provide the request, response object, if done after the end of development, to request, response should be more familiar. The front-end request can be initiated by a URL or by using the request object, and request can be reused. But where is response used? Before the service worker appears, the front end does not send oneself the message, but has the service worker, can after intercepts the request to send back own response according to need, to the page, this common request result does not have the difference, this is the response application. Message Event

A message can be sent between the page and the Serviceworker through the Posetmessage () method, and the message sent is received through the messages event.

This is a two-way process, the page can send messages to the service Worker,service worker can also send messages to the page, because of this feature, you can use the service worker as a middle link, so that a domain name or sub-domain name under the multiple pages can be freely communicated. Install Events

This event is triggered when the page is loaded. Often used to cache offline pages, the cached pages in the event are returned to the user when the network is disconnected. acrive Events

This event is triggered when the service worker is triggered. After the code is updated, it is often necessary to perform a management cache operation in the activate callback. Because you will need to erase the old data before. We do this when we're activate instead of install because if we execute it immediately at install, the old version of the data that is still running is broken. 3. Service Worker Example

Again: All the code below please see GitHub download full version

The example is simple, when I access the page when I connect to the network, the result is as follows:

The console is as follows:


Explain the scope here, which is the domain that can intercept the request.
When I use the Chrome-> Developer tool in Chrome-> New Work-> offline analog disconnected, refresh the page:

The same URL, returned a different page. Indicates that the service worker successfully intercepted the original request (if not intercepted, the page could not be accessed as indicated above).

The main code and comments are as follows:
Index.html

<! DOCTYPE html>

Service-worker.js

' Use strict ';
var cacheversion = 0;
var Currentcache = {offline: ' Offline-cache ' + cacheversion};

Const OFFLINEURL = ' offline.html '; This.addeventlistener (' Install ', event => {event.waituntil caches.open (currentcache.offline). Then (function (CAC
    He) {return Cache.addall (['./offline.svg ', OfflineURL]);
})
  );

}); This.addeventlistener (' Fetch ', event => {if (Event.request.mode = = ' Navigate ' | | (Event.request.method = = ' Get ' && event.request.headers.get (' Accept '). Includes (' text/html ')) {Event.respondwith fetch (event.request.url). catch (Error => {//return the offline PA
        GE return Caches.match (offlineurl);
  })
     );
                        } else{Event.respondwith (Caches.match (event.request). Then (function (response) { Return Response | |
                    Fetch (event.request);
      })
            ); }
});

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.