Thoughts on service workers
What?
- A WEB API developed and promoted by Chrome to provide advanced and sustainable background processing power for WEB applications. The WEB API standard was drafted in 2013, incorporated into the W3C WEB Standards Draft in 2014, and is currently in the draft stage.
- Service Workers essentially act as a proxy server between the Web application and the browser, and can also act as a proxy between the browser and the network when the network is available. They are designed, among other things, to enable the creation of an effective offline experience, intercept network requests and take appropriate action based on whether the network is available and whether updated resources reside on the server. They also allow access to push notifications and background synchronization apis
- After the page is registered and installed successfully, it runs in the background of the browser and is not affected by page refresh. It can monitor and block HTTP requests of all pages within the scope. Combined with Fetch API, Cache API, Push API, postMessage API and Notification API, common functions of native applications such as offline Cache, message Push and silent update can be realized in browser-based Web applications. To provide a better and richer use experience for web applications.
- The js must run in the localhost domain or HTTPS domain, and the registered JS must be in the same domain as the site
- compatibility
- Application Scenario (MDN)
- Background Data Synchronization
- Respond to resource requests from other sources
- Centrally receive computationally expensive data updates, such as geolocation and gyroscope information, so that multiple pages can leverage the same set of data
- Compilation and dependency management of CoffeeScript, LESS, CJS/AMD modules on client side (for development purposes)
- Background service hook
- Custom templates are used for specific URL patterns
- Performance enhancements, such as prefetching resources that a user might need, such as the last few images in an album
How?
Quick learning
-
Add the following script to the HTML
if (navigator.serviceWorker ! = null) {
navigator.serviceWorker.register('/service-worker.js')
.then(function(registration) {
console.log('Registered events at scope: ', registration.scope);
});
} else {
Console (' sw not supported ')
}
Copy the code -
service-worker.js
var cacheStorageKey = 'blog-pwa-2018060100'
var cacheList = [
'/',
"/index.html",
"/statics/css/swiper.css",
"/statics/js/swiper.js",
"/statics/images/1.jpeg",
"/statics/images/6.jpeg",
"/statics/images/7.jpeg"
]
this.addEventListener('install', e => {
e.waitUntil(
caches.open(cacheStorageKey)
.then(cache => cache.addAll(cacheList))
.then(() => self.skipWaiting())
)
})
this.addEventListener('fetch', function(e) {
e.respondWith(
caches.match(e.request).then(function(response) {
if (response ! = null) {
return response
}
return fetch(e.request.url)
})
)
})
Copy the code -
After the above processing, the site can simply have offline ability.
Something to think about
- How to update service-worker.js quickly and easily?
- Since service-worker.js needs to be homologous with the site, the project separated at the front and back ends needs the back end to forward the request of service-worker.js to a resource controlled by the front end
- If the site’s HTML is controlled by the front-end rather than the back-end template, the front-end needs to update the service-worker request when it goes live, with either a timestamp or an MD5 stamp to prevent it from being cached by HTTP
- If your site’s HTML is not controlled by the front end, it is best to set it to no cache time, or a very short cache time, such as 5s, in order to keep service-worker.js up to date. Or the request URL is automatically stamped each time, which is essentially no cache time. Avoid the need to update backend templates every time you go online.
- How do I update resources cached by serviceWorker?
- Updating service-worker.js re-executes events such as Install Actived, in which old caches are removed and new caches are added
- The fetch will be executed because the old activated service worker is still running. Cache. Match is used in fetch to determine whether the cache has been hit. Cache. match is a request match, so if the URL does not change, it will return true, so that response is directly fetched from the cache, causing the resource fetched from the previous version when the page is opened for the first time.
- So to update on the front end, the URL must change to update correctly the first time it is opened
- Automatic generation of service-worker.js?
- Sw-precache and SW-Toolbox are early tools developed by Google; Sw-precache is a cache tool for the cache-first policy, which automatically generates sw.js based on the hash file. After the fetch hits the cache, it directly returns to the cache and then adds or deletes the cache based on the latest cache list. Sw-toolbox is used to cache some third-party resources and added the ability to customize caching strategies based on routes
- Google will no longer maintain either tool, but the ultimate solution is WorkBox, which is more feature-rich and easier to use with plug-ins.
- Workbox-webpack-plugin NPM package, CLI, Webpack workbox-webpack-plugin
How much benefit?
- Need an offline experience?
- Presentation is fine, but for projects that require online availability, it may not really be necessary.
- The offline function can ensure the availability of low-speed network to a certain extent
- What are the advantages of the SW cache over the normal HTTP cache?
- More control, more granularity, caching time, updates are all done by the front-end code, rather than configuration on servers like Nginx.
- There should be no difference in speed, it’s all cache, and it should all be stored on hard disk.
- Push notification
- Unavailable in China
What are the risks with this new technology
- Does it increase the likelihood of a white screen?
- Add sw, and the front end controls the return of the request. Request directly in sw for some logical judgment, and then either from the cache, or directly to the CDN to obtain, then the SW needs to consider all kinds of circumstances, do a good bottom, to avoid the problem of SW, resulting in the request error. Sw is best written with a script generated by SW-Precache or Workbox, or with reference to the script generated by it.
- Browser compatibility
- At present, BOTH IE and Safari have supported SW, but the apis and methods used in it, such as Cache and Fetch, are not well compatible, so we need to make a judgment
Refer to the article
Service worker DRAFT MDN Service worker API website Incremental Enhancement Experience (PWA) transformation: PWA practice with Service Worker and cacheStorage and offline development sw-precache sw-toolbox workbox