Web Push API and Service Worker 1
TL;DR
try the demo here: https://github.com/leon0707/web_api_worker
Why
Why web developers need the push API?
Push API gives web applications the ability to receive messages pushed to them from a server. This lets developers deliver asynchronous notifications and updates to users that opt in, resulting in better engagement with timely new content.
use cases
1. News sites push the latest breaking news to opt-in users.
2. Text message apps push notifications to users when new messages are sent.
Background knowledge
Javascript is a single threaded language, which means it can only execute one piece of code at a time. So letting the js main thread wait for the messages from web push service is not acceptable, because it will block other operations on the web pages.
Fortunately, JavaScript and the browser can work together to provide an efficient solution. We will use service work, a type of web worker.
Web worker
Web worker runs scripts in a background thread. It can perform tasks that don’t interact with DOM(you cannot manipulate DOM in a web worker script).
The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.
Data is sent between workers and the main thread via a system of messages — both sides send their messages using the postMessage()
method, and respond to messages via the onmessage
event handler. The data in the message is copied rather than shared.
Check running workers in firefox about:debugging#/runtime/this-firefox
, in chrome chrome://inspect/#service-workers
First, create a worker script
Basically, this web worker will wait for the client(main thread) to send it messages. Depending on the content of the messages, web worker conduct operations(cannot be on DOM).
self
inside the web-worker.js
refers to the web worker script itself not windows object.
Worker will listen to message
event. The worker can throw an error and let main thread to handle it.
Another way to listen to message event
onmessage = function(event) {
console.log(event.data);
postMessage('send this msg back to main js');
}
Create the main script
The client in the main thread initializes a worker, and sends a message to it first. Then it will listen to the messages sent by the worker.
postMessage
can post objects like string, JSON, array... Data passed between the main page and workers is copied, not shared. Objects are serialized as they're handed to the worker, and subsequently, de-serialized on the other end using structured clone algorithm.
If the web worker is closed or terminated, the web worker thread will be terminated too.
More details can be found:
https://developer.mozilla.org/en-US/docs/Web/API/Worker
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
Two different ways to use workers
- Dedicated workers
A dedicated worker is only accessible by the script that called it - Shared workers
A shared worker is accessible by multiple scripts
Shared workers and all other scripts need to communicate via ports.
Service Worker
Service workers function like a proxy server, allowing you to modify requests and responses, replace them with items from its own cache, and more.
A service worker is an event-driven worker registered against an origin and a path.
Keys
- run in a worker context. no DOM
- run on a single thread. not blocking
- fully async. not support sync functions localStorage, sync xhr
- only run over HTTPS except for locally hosted sites, and can not be accessed in private browsing mode
Lifecycle
- Download
- Install
- Activate
Use case:
- Background Sync, which makes the offline experience of an app better
When client registers the service worker, a new thread is generated to handle to installation of the service worker.
An InstallEvent
is dispatched when the installation of service work starts. In the example above, caches
opens a cache object, if the cache object doesn’t exist, a new cache is created. Then the cache object adds all resources in itself by corresponding response objects or URLs. If the cache operation fails, service worker fails to be installed too, and it is not activated.
Service worker won’t be installed again until next day(24 hours), or a new service worker script replaces the old one.
Once the installation succeeds, the service worker is activated and is ready to listen to the FetchEvent
.
Details about caches
:
https://developer.mozilla.org/en-US/docs/Web/API/Cache
Jump to the next article: https://medium.com/@leonfeng/web-push-api-and-service-worker-2-20db00a4f96f