Service workers
Build web apps with offline support,
push notifications and background sync.
- a script running in a background thread
separate from the main UI execution thread
web workers
👷🏻
- Dedicated workers - one per page script
worker types
- Shared workers - utilized by multiple page scripts, windows, IFrames, etc.
from the same domain
- Service workers - Focused on the network
Act as proxy servers
A service worker acts as a proxy server.
What is a service worker?
👷🏻
It intercepts network requests, decides how to respond based on network availability, and updates assets cach.
Offline support
service worker advantages
👷🏻
Push notifications
Perceived performance / UX
Background sync
Example use cases
👷🏻
Caching assets enables users
to access the web app even when they're offline: lodash
Offline access
Pre-fetch resources
such as the next few pictures in a photo album Pinterest
Background sync
Sync data with a server even when the application isn't actively being used.
Analytics Tracking
collect interactions, page views, and other metrics, even offline, and send those to the server in the background.
Push notifications
Receive push notifications from a server, even when the web app is not open in the browser.
Stubbing fake network responses, for testing: msw
API mocking
Auth
Service workers can handle authentication and authorization logic, like auto token renewal etc.
Restrictions
👷🏻
SW can only control pages within their same origin and cannot access other domains without explicit permission.
Same Origin Policy
HTTPS only
Service workers require HTTPS to function, ensuring they're not vulnerable to man-in-the-middle attacks.
Browser support
While most modern browsers support service workers,
we still need to check and consider old browsers.
No DOM access
SW cannot manipulate the DOM or access the Window object directly. They need to ask the main thread to do so.
SW can't access localStorage, sessionStorage & cookies
However, they do have access to IndexDB and files Cache.
Limited storage
sw LIFECYCLE
👷🏻
v2
v1
v1
v1
v2
v2
Service workers
By Yariv Gilad
Service workers
- 111