Tutorial by Examples

// Check if service worker is available. if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').then(function(registration) { console.log('SW registration succeeded with scope:', registration.scope); }).catch(function(e) { console.log('SW registration failed...
A web worker is a simple way to run scripts in background threads as the worker thread can perform tasks (including I/O tasks using xmlHttpRequest) without interfering with the user interface. Once created, a worker can send messages which can be different data types (except functions) to the JavaSc...
main.js A service worker is an event-driven worker registered against an origin and a path. It takes the form of a JavaScript file that can control the web page/site it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashio...
Dedicated Workers A dedicated web worker is only accessible by the script that called it. Main application: var worker = new Worker('worker.js'); worker.addEventListener('message', function(msg) { console.log('Result from the worker:', msg.data); }); worker.postMessage([2,3]); worker.j...
Once you are done with a worker you should terminate it. This helps to free up resources for other applications on the user’s computer. Main Thread: // Terminate a worker from your application. worker.terminate(); Note: The terminate method is not available for service workers. It will be term...
After your service worker is registered, the browser will try to install & later activate the service worker. Install event listener this.addEventListener('install', function(event) { console.log('installed'); }); Caching One can use this install event returned to cache the assets ne...
Since workers run in a separate thread from the one that created them, communication needs to happen via postMessage. Note: Because of the different export prefixes, some browsers have webkitPostMessage instead of postMessage. You should override postMessage to make sure workers "work" (n...

Page 1 of 1