A simple service worker
suggest changemain.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 fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available.)
Source: MDN
Few Things:
- It’s a JavaScript Worker, so it can’t access the DOM directly
- It’s a programmable network proxy
- It will be terminated when not in use and restarted when it’s next needed
- A service worker has a lifecycle which is completely separate from your web page
- HTTPS is Needed
This code that will be executed in the Document context, (or) this JavaScript will be included in your page via a <script>
tag.
// we check if the browser supports ServiceWorkers
if ('serviceWorker' in navigator) {
navigator
.serviceWorker
.register(
// path to the service worker file
'sw.js'
)
// the registration is async and it returns a promise
.then(function (reg) {
console.log('Registration Successful');
});
}
sw.js
This is the service worker code and is executed in the ServiceWorker Global Scope.
self.addEventListener('fetch', function (event) {
// do nothing here, just log all the network requests
console.log(event.request.url);
});
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents