A CheatSheet containing getting started, tips, tricks, best practices, code and more about ServiceWorker.
- Service Worker Cookbook
- Introduction to Service Worker
- The offline cookbook
- Using Service Workers today
ServiceWorker is a background worker, it gives us a JavaScript context to add features such as push messaging, background sync, geofencing and network control.
To begin, you need to register for a ServiceWorker from your page:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/worker.js').then(function(reg) {
console.log('😃', reg);
}, function(err) {
console.log('😭', err);
});
}
As you can see, .register
take a URL for your worker script and returns a promise. The ServiceWorker script must be on the same origin as your page.