Background:
In recent days, the leader asked to make a database backup function. Click a button on the front page to call a back-end service. The back-end will back up the database. After the backup is successful, the status code will be returned to the back-end The train of thought is very clear and the logic is very clear However, there is a problem that it takes a long time for the back-end to back up the database. During this time, how should the front-end handle this process and how should the back-end handle it after returning? I thought carefully for a while, and suddenly a light came into my mind. A word appeared in my mind, serviceWorker
Introduction to serviceWorker:
Service Worker It's a kind of Web Worker . It is essentially a JavaScript file running separately from the main browser thread. It can intercept network requests, cache resources, retrieve resources from the cache, and deliver push messages.
serviceWorker function:
1. Network agent, forward request, forge response 2. Offline cache 3. Message push 4. Background messaging
Service Worker advantages and typical application scenarios
1. Offline caching: it can store unchanged or rarely changed resources in H5 applications on the client for a long time, improve loading speed, reduce traffic consumption and reduce server pressure. Such as moderate and severe H5 games, web information client with independent framework data, web mail client, etc
2. Message push: activate sleeping users, push instant messages, announcements and notifications, stimulate updates, etc. Such as web information client, web instant messaging tools, h5 games and other operating products.
3. Event synchronization: ensure that the tasks generated by the web can be completed smoothly even when the user closes the web page. Such as web mail client, web instant messaging tools, etc.
4. Timing synchronization: the timing synchronization event in the Service Worker script is triggered periodically, which can be used to refresh the cache content in advance. Such as web information client.
Implementation idea:
After a brief introduction to serviceWorker, let me talk about the implementation idea
First, when the user clicks the database backup button on the page, a serviceWorker's postMessage method is triggered to enter the serviceWorker thread to call the background interface. After the background interface returns, the client's postMessage function is triggered to display the information on the page in the form of notification
In this way, you can do whatever you want after clicking the button. You don't have to stay on this page. Wait until the back end returns the interface information, and then notify the user of OK in the form of browser notification!
Specific code:
Here I'll show you a demo
First create an index HTML and an SW js
index.html is a page,
sw.js is the thread processing function of serverWorker
First look at index html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Service Worker Demo</title> </head> <body> <button id='sendBtn'>Backup database</button> <script> function showNotice() { Notification.requestPermission(function (perm) { if (perm == "granted") { var notification = new Notification("You have a new notice:", { dir: "auto", lang: "hi", tag: "message", body: "Database backup succeeded!!!" }); } }) } (function() { if ('serviceWorker' in navigator) { var sendBtn = document.getElementById('sendBtn'); navigator.serviceWorker.register('sw.js'); navigator.serviceWorker.addEventListener('message', function (event) { showNotice() }); sendBtn.addEventListener('click', function() { navigator.serviceWorker.controller.postMessage(); }) } })(); </script> </body> </html>
A button, a trigger event and a notification function are so simple
Take another look at SW How is JS handled
self.addEventListener('message', function(event) { var promise = self.clients.matchAll() .then(function(clientList) { setTimeout(function(){ clientList.forEach(function(client) { client.postMessage({ client: senderId, message: event.data }) }) },3000) }) if (event.waitUntil) { event.waitUntil(promise); } }); self.addEventListener('activate', function(event) { event.waitUntil(self.clients.claim()); })
After listening to the message event and processing it, push the message to all browser windows after 3 seconds, and then Ok
reference material
1,https://www.w3.org/TR/service-workers/
2,https://developers.google.com/web/fundamentals/getting-started/primers/service-workers
3,https://developers.google.com/web/fundamentals/getting-started/codelabs/offline/