With service worker and Cachestorage Caching and offline development (reprint)

Source: Internet
Author: User
Tags addall home screen

First, cache and offline development

That's HTML5. Offline development, we usually first reaction is the use of HTML5 manifest cache technology, this technology has been around for many years, I have known many times before, but also seen some practice cases, but has never been introduced in the blog, because not optimistic.

Why don't you watch it? In one sentence, "input-output ratio is somewhat low".

For the Web application, the drop line can not be used as a matter of course, there will never be a developer because the Web page does not open when the test mm bug, or by the user complaints, so, our web page does not support offline completely does not have any impact. But if we want to support offline, will find that I put the energy and cost AH is really not small, say a little, HTML5 manifest cache technology needs to serve the service side directly to let the cost rub rub up, because it is not only the front end of this job, it is likely to need cross-team collaboration, This thing immediately on the long-winded, development time wordy, later maintenance also wordy.

While supporting off-line revenue, I have estimated that it is lower than support for accessibility gains. Therefore, in the commercial perspective, if a technical cost is relatively high, the income is relatively small, is not recommended practical application. Developers like to play some funky cool new technology in important projects since Hi is understandable, but only if the benefits are obvious. If it's just self-hi, leaving a bad stall, there is a need to be vigilant, business awareness and professional literacy explanation still needs to be improved.

Cushion so much, is to turn the next article to introduce the caching technology.

In this paper, based on service worker and Cachestorage cache and offline development, routines are very fixed, no intrusion, and pure language, direct copy and paste can be implemented cache and offline functions, pure front-end, without server coordination. A seemingly cool feature as long as the copy and paste can be achieved, the cost is extremely low, small white in small white can also get started.

Because the cost is almost negligible, at this time the offline function support of the input-output ratio is quite high, experience tells me this technology after the popularity and popularity of the possibility is very high, so can't wait to share to everyone.

Before we start the case, we need to understand a few concepts first.

Second, easy-to-understand way to introduce service Worker

The service worker's straightforward translation is the "staff", seemingly casual translation, but actually the right way out of the essence of service workers.

For example, if we go to McDonald's for Ye Xiu's collection card, as shown in:

The actual process is the need for a "service staff", customer ordering, pay, service personnel to provide food and Ye Xiu card, back to the customer's hands.

If from the perspective of maximizing utilization, the service staff here is actually redundant, the customer directly pay to take goods faster, and this direct request policy is the practice of Web requests, the client sends the request, the server returns the data, the client displays again.

After all these years, it seems that there is no problem with this data request strategy for the Web, so why should we add a "service person"-service worker in the middle?

The main thing is the user to deal with some special scenarios and requirements, such as offline processing (Sir, this sold out), such as the message push (Sir, your burger is good ...) such as Offline apps and message push are the advantages of native apps over web apps today.

So, the purpose of the Service worker is to allow the Web app to compete in real sense with the native app.

Service Worker Concepts and usage

The page running in our usual browser window runs the main JavaScript thread, and the DOM and window global variables are accessible. While the service worker is another thread that walks, it can be understood as a thread that runs silently behind the browser, out of the browser form, so that the window and the DOM are inaccessible, and we can use access to the self global context at this point, see this short article: " Understand the global object window.self and global scope self "in JS.

Because the service worker walks on another thread, even if the thread boil does not block the main JavaScript thread, that is, it does not cause the browser page to load. Also, because the service worker is designed to be completely asynchronous, the synchronization API (such as XHR and localStorage ) cannot be used in service worker.

In addition to the above restrictions, the service worker to our agreement also has the request, is must be the https agreement, but the local development also to make an https agreement is very troublesome, fortunately also is humanized, the service worker in http://localhost or http://127.0.0.1 It is also possible to run in this local environment. If we want to make a demo page for other small partners to see, we can use GitHub (because it is a https protocol), for example, I have built a special Https-demo small project, specifically to place some need to https deal with the demo page, I believe that without https The technical scene will be more and more.

Finally, service workers are heavily used Promise because they typically wait for a response to continue and return a successful or failed action based on the response, which is ideal for these scenarios Promise . If you do Promise not know well, you can first read my previous article: "ES6 JavaScript Promise Perceptual Cognition", and then read: "JavaScript promise mini-book (Chinese version)".

Life cycle of Service worker

Let's take a look at an example, the following HTML and JS code:

<script src= "./static/jquery.min.js" ></script><script>if (' Serviceworker ' in navigator) {$ (' #    Issupport '). Text (' Support '); Start registering service workers Navigator.serviceWorker.register ('./sw-demo-cache.js ', {scope: './'}). Then (function (registration)        {$ (' #isSuccess '). Text (' registered success ');        var Serviceworker;            if (registration.installing) {serviceworker = registration.installing;        $ (' #state '). Text (' Installing ');            } else if (registration.waiting) {serviceworker = registration.waiting;        $ (' #state '). Text (' Waiting ');            } else if (registration.active) {serviceworker = registration.active;        $ (' #state '). Text (' active ');            } if (Serviceworker) {$ (' #swState '). Text (serviceworker.state); Serviceworker.addeventlistener (' StateChange ', function (e) {$ (' #swState '). Append (' &emsp; status changed to ' + E.tar            Get.state);        }); }    }).catch (function (Error) {$ (' #isSuccess '). Text (' Registration not successful '); });} else {$ (' #isSupport '). Text (' not supported ');} </script>

The code is simple to determine whether the browser supports service workers and logs the service worker's life cycle (the current state).

In Chrome, when we first visit the page that contains the above code, the result is this:

will see: installing→installed→activating→activated.

This process of state change is actually the response of the service worker's life cycle.

When we refresh this page again, the result is this:

The registration success status is displayed directly.

The life cycle of Service worker registration is this:

    1. download– Download the registered JS file
    2. install– Installation
    3. activate– activation

Once the installation is complete, how to register JS does not change, then directly displays the current activation state.

However, the actual development scenario is more complex, leaving the service worker with some other state. For example, this:

Appeared waiting , how did this come about? We modified the service worker registration JS and then overloaded when the old service worker was still running, and the new service worker was installed waiting to be activated. We open the Developer Tools panel, Application→service Workers, which might be like this:

At this point, our page under the strong brush will become this, the activation:

Refresh again and return to the registered state.

Then, these corresponding states, the Service worker is captured with the corresponding event name, as follows:

Self.addeventlistener (' Install ', function (event) {/* * after installation ... */});
Self.addeventlistener (' Activate ', function (event) {/* * after activation ... */});

Finally, the Service worker also supports fetch events to respond to and intercept various requests.

Self.addeventlistener (' Fetch ', function (event) {/* * after request ... */});

Basically, all of the current service worker applications are based on the above 3 events, for example, the caching and offline development to be described in this article, to ‘install‘ cache files, to ‘activate‘ cache updates, ‘fetch‘ to intercept requests to directly return cached data. Together, they form the complete cache control structure.

Service worker Compatibility

Desktop Chrome and Firefox are available, IE is unavailable. Mobile Chrome is available and is expected to be quickly supported later.

Iii. Understanding Caches and Cachestorage

CacheAnd CacheStorage are all interfaces under the service Worker API, as follows:

Among them, dealing directly with the Cache request, CacheStorage and dealing with the cache object, we can directly use the global caches properties to access the Cachestorage, for example, although the API shows that CacheStorage.open() , but we actually use the time, directly caches.open() can.

CacheAnd CacheStorage the advent of the browser to let the cache type one more: Before there are memorycache and DiskCache, now a serviceworker cache.

As Cache CacheStorage for the specific additions and deletions to the API to go directly here to find, Service Worker API Knowledge volume is amazing, if you want to learn the system, it can be prepared enough psychological.

However, if we just want to apply one or two-point practical tips to actual projects, it's a lot easier. For example, we want to incrementally enhance support for off-line development and more flexible cache control on our PC project on the latter mobile page, directly referencing the following routines!

Iv. fixed routines developed offline with service worker and Cachestorage
  1. A service Worker is registered on the page, for example:
    if (' Serviceworker ' in navigator) {    navigator.serviceWorker.register ('./sw-demo-cache.js ');}
  2. sw-demo-cache.jsThis JS copy the following code:
    var VERSION = ' V1 ';//cache Self.addeventlistener (' Install ', function (event) {Event.waituntil (Caches.open (VERSION). Then ( function (cache) {return cache.addall (['./start.html ', './static/jquery.min.js ', './static/mm1.    JPG ']); })  );});/      /cache update Self.addeventlistener (' Activate ', function (event) {Event.waituntil (Caches.keys (). Then (function (cachenames) {  Return Promise.all (Cachenames.map (cachename) {//If the current version and cached version are inconsistent if (CacheName!==          VERSION) {return caches.delete (cachename);    }        })      ); })  );});/ /captures the request and returns the cached data Self.addeventlistener (' Fetch ', function (event) {Event.respondwith (Caches.match (event.request). catch (  function () {return fetch (event.request);    }). Then (function (response) {Caches.open (VERSION). Then (function (cache) {Cache.put (event.request, response);    });  return Response.clone ();  }). catch (function () {return Caches.match ('./static/mm1.jpg '); }));}); 
  3. cache.addAll()Replace the cached file array in the method with the file array you want to cache.

Congratulations, simple 3 steps, copy, paste, change the path. Your website already supports the service worker cache, even offline can freely access, support various websites, PC and mobile kill, unsupported browser does not have any effect, support browser natural offline support, want to update the cache, v1 replace v2 can, so easy!.

Seeing is believing, you can click here: with service worker and Cachestorage cache and offline development demo

To enter the page, we tick the offline in the network, such as:

When the results are refreshed, the page will still load normally, as shown in GIF screenshot:

Our off-line functionality was achieved in this, surprisingly simple and practical.

V. The relationship with PWA technology

PWA is all called "Progressive Web Apps", a progressive web app. Significant benefits, such as:

The core technologies of PWA include:

    • Web app manifest– Add app icon on home screen, define phone title bar color, etc.
    • Service worker– caching, offline development, geo-location information processing, etc.
    • App shell– shows the main structure of the app first, populates the master data, and shows a better experience faster
    • Push notification– message Push, previously written "simple understanding of Web Notification Desktop notifications in HTML5"

It is visible that Service workers are only part of the PWA technology, but are independent of PWA. That is, although the PWA technology is geared toward the mobile side, it does not affect our progressive use of service workers on the desktop, and the revenue may be higher than expected, considering that our factory users 70%~80% are chrome cores.

VI. more application scenarios for Service worker

Service worker can be used in addition to caching and offline development, there are many scenarios, for example (refer to from MDN):

    • Background data synchronization
    • Respond to resource requests from other sources.
    • Centrally receive data updates that are computationally expensive, such as geolocation and gyroscope information, so that multiple pages can take advantage of the same set of data
    • Module compilation and dependency management (for development purposes) at the client for COFFEESCRIPT,LESS,CJS/AMD
    • Background service Hooks
    • Custom templates for specific URL patterns
    • Performance enhancements, such as prefetching of resources that a user might need, such as the number of images in a photo album

Start your own brain, and many ideas can be implemented directly from the front.

For example, I came up with the idea that when a refactoring person writes a high-fidelity prototype, it can intercept and return the simulation data directly in the service worker without relying on the web environment, and the entire project is only clean HTML, CSS, and JS.

All right, that's all.

More content, hasty behavior, mistakes are unavoidable, please correct me!

Also welcome to exchange, thanks for reading!

With service worker and Cachestorage Caching and offline development (reprint)

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.