Does your web application support offline access and policy caching?

Does your web application support offline access and policy caching?

Indulge in the beauty of life. Look at the stars and imagine that you are running with them yourself. ——Philosopher, Mark Aurelius

• WeChat public account " JavaScript Full Stack " • Nuggets " Master of Oneness " • Bilibili " Master of Oneness "

Performance is always trade-offs between time and space. The optimization of computer systems requires the help of various caching strategies, from CPU to memory, from interface to peripheral. If one day, hardware cost and difficulty of implementation are no longer obstacles, perhaps the word "optimization" will disappear.

At present, the front-end faces more optimizations and challenges, complicated terminal environments, various browser kernels, and browser devices of different sizes. Compatibility needs to be done. Complex and unstable network environment, more and more resources, optimization needs to be done. We are not unfamiliar with caching, but we want subjective caching. What I want to cache, how long the cache is, and the strategy for caching and requesting resources are all determined by ourselves, which service workercan help us achieve it.

Use service workerbefore, you need to create a registration document, you may wish to create a project named in the sw.jsdocument

console.log('Hello, I am sw.js file')

Then in the application registered by this document, the application can be done by the following code service workerregistration, on the back of service workerthe relevant treatment, sw.jsperformed file.

<script>
   //Check if the current browser supports service workers
  if ('serviceWorker' in navigator) {
   //Make sure that the resource is loaded, and then register the service worker
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('/sw.js');
    });
  }
</script>

Refresh the page, you can see the console print this sentence indicates service workersuccessful registration

Open the console Application, everything is under control, the service workerregistration is successful

Here is complete, complete service workerthe registration on its associated configuration and processing, we went sw.jsdefined in the file it!

Google's standard unified api operation, based on service workerpolicy cache library, which has the following characteristics people praise

1.Precaching2.Runtime caching3.Strategies4.Request routing5.Background sync6.Helpful debuggin7.Greater flexibility and feature set than sw-precache and sw-toolbox

I remembered a sentence, simple concepts are complicated, popular concepts are mystified, this is to show their extraordinary,? Just kidding. I believe that most people see these concepts as silly . We only need to focus on one concept: caching , which is strategic, and what is stored can be controlled. It also provides us with ideas for developing offline applications.

Use Workbox

Remember the sw.jsfile? Now we put the center on it, because follow-up related operations need to be performed in this file, ready? go!

###Import Workbox

1. the sw.jsintroduction of the first line workbox.jssyntax

importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js');

Has the import been successful? Write a piece of code to test it!

if (workbox) {
  console.log(`Yay! Workbox is loaded ?`);
} else {
  console.log(`Boo! Workbox didn't load ?`);
}

When changes are complete, back to the browser, then refresh the browser without any change, where the need to remind you that you've changed your service workerregistration documents need to restart or terminate the update.

Start using Workbox

Workbox Defined a standard unified API, let's see how to use the API provided by it to gradually optimize the project

Route request definition cache

In Workboxthe most central concept to the number of policy-based routing cache, and seize the two key words here, based on the routing , policy . The next focus is on how to based on routing, how to reflect the strategy.

Most front-end resources are by HTTPrequest come, including js, css, pictures, etc., since these elements are needed request, I can not after the request is issued, to do some deal with it? Just like the landlord rents a house, the information between the landlord and the tenant may be asymmetrical. At this time, an intermediary appears. It can do some processing before the landlord rents out the house, such as adding an intermediary fee. When a web page initiates a resource request, we can also make some decisions, whether to take it from the cache or to request it. For different resources, it is achieved through the resource request address, which is based on routing . Examples are as follows

workbox.routing.registerRoute(
 /\.js$/,
  …
);

The above code we define a route cache strategy, namely: all the suffix .jsof the policy will enter a request for processing, then, what we need to do to deal with it? There will be defined for different resources match the routing policy on cache, for example, we asked to specify resource network priority request

workbox.routing.registerRoute(
 /\.js$/,
  new workbox.strategies.NetworkFirst()
);

At this time, if the js file is introduced into the project, this cache will take effect, assuming the project is introduced hello.js

console.log('hello js file')

Introduce in html

<script src="./hello.js"></script>

When you come to the browser, first update the service worker. The method is described above and will not be repeated here. Immediately after refreshing, we can see the printed log, indicating that the configuration is successful

Everything is difficult at the beginning. We have overcome this first problem. Next, we will expand horizontally and choose different strategies for the configuration of different types of files. Let's first look at the configuration of processing different files, it's very simple

String mode

workbox.routing.registerRoute(
    '/logo.png',
    handler//handler is the callback function of the cache strategy, usually refers to the'cache strategy function' that will be lowered later
);
workbox.routing.registerRoute(
    'https://some-host/some-path/logo.png',
    handler
);

Regular expression

workbox.routing.registerRoute(
 //Cache pictures.
 /\.(?:png|jpg|jpeg|svg|gif)$/,
  handler
);

Function form

//Match the request route by function
const matchFunction = ({url, event}) => {
   //If the request route matches, return true, or return a parameter object for the handler to receive and process
    return false;
};

workbox.routing.registerRoute(
    matchFunction,
    handler
);

The handler of the above code is the caching strategy API provided by workbox, and the following are commonly used

Strategy name

API

staleWhileRevalidate

When the requested route has a corresponding Cache result, it will be returned directly. When the Cache result is returned, a network request will be initiated in the background to get the request result and update the Cache. Return result

networkFirst

Network-first strategy

cacheFirst

Get the result directly from the Cache. If there is no result in the Cache, it will initiate a network request, get the result of the network request and update the result to the Cache cache, and return the result to the client

networkOnly

Force the use of normal network requests

cacheOnly

Use Cache directly to cache the results

In general scenarios, the above 5 strategies can basically meet the requirements, if there are still unsatisfactory conditions, you can customize the strategy

workbox.routing.registerRoute(
    ({url, event}) => {
        return {
            name:'workbox'
        };
    },
    ({url, event, params}) => {
       //The result returned is: A guide on workbox
        return new Response(
            `I am ${params.name}`
        );
    }
);

An example is given below to introduce the use of different strategies

For example, image resources are not frequently changed, so you can choose a priority cache strategy and group this type of resources. The specific content can be found in Application->Cache View

workbox.routing.registerRoute(
 /\.(?:png|jpg|jpeg|svg|gif)$/,
  new workbox.strategies.CacheFirst({
    cacheName:'my-image-cache',
  })
);

Related files such as js can be selected appropriately for network priority

workbox.routing.registerRoute(
 /\.html$/,
  new workbox.strategies.NetworkFirst()
);

workbox.routing.registerRoute(
 /\.js$/,
  new workbox.strategies.NetworkFirst({
    networkTimeoutSeconds: 3,
  })
);

Use workbox in webpack

First install workbox-webpack-plugin, choose to install using npm

npm install --save-dev workbox-webpack-plugin

Configure the plugin in the webpack configuration file

const workboxPlugin = require('workbox-webpack-plugin');

//...
webpack({
    plugins: [
       //...
        new workboxPlugin({
            swSrc:'./src/sw.js',
            swDest:'./dist/sw.js',
            globDirectory:'./dist/',
            globPatterns: ['**/*.{html,js,css}'],
        })
    ]
   //...
});

To use the Webpack plug-in provided by workbox, you must app/sw.js contain the following code to the complete list of pre-cached content injection work

workbox.precaching.precacheAndRoute(self.__precacheManifest || []);

So far, can you imagine supporting offline access through our configuration of resources in the project? Through these configurations, application performance can be greatly improved, strategy, what you want is the most beautiful.

I am one, goodbye heroes!

Reference: https://cloud.tencent.com/developer/article/1664347 Does your web application support offline access and policy caching? -Cloud + Community-Tencent Cloud