Service Worker
What is a Worker?
It is an interface of web Workers API, which represents a backgound task that can be easily created and send messages back to its creator.
Creating a Worker
Worker()
- creates a web worker that executes the script at the specified URL.
What is a Service Worker?
It acts as a proxy servers between the the web applications, browser and the network.
They are intended to enable the creation of effective offline experience, intercept network requests and take appropriate action based on the netork availability.
It is a event-driven worker registered against an origin and a path
How does a Service Worker work?
It takes a form of a java script file which control the web-page that it is associated with it by:
- intercepting and modifying navigation and resource request
- caching resources
Service Worker - conditions applied*
- no DOM access
- local Storage cannot be used
- only run over HTTPS
- cannot be used when the user is in private browsing mode
Concept and Usage
Registration:
ServiceWorkerContainer.register()
If the registration is successful your service worker will be downloaded to the client and attempt to install/activate for URLs accessed by the user.
Download:
The service worker is immediately downloaded when a user first accesses a service worker - controlled site/page
After that, the service worker is downloaded every 24 hours or so
Installation:
Installation is attempted when the downloaded file is found new.
Activation:
- If the service worker is made available, installation is attempted, then after a successful installation, it is activated.
- If there is an existing service worker available, new version is downloaded in the background, but not yet activated - worker in waiting
- It is only activated when there are no longer any pages, that are still using the old service worker
- As long as there are no more pages to be loaded, the new service worker activates - active worker
SERVICE WORKER- Sample code
// register service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw-test/sw.js', { scope: '/sw-test/' }).then(function(reg) {
if(reg.installing) {
console.log('Service worker installing');
} else if(reg.waiting) {
console.log('Service worker installed');
} else if(reg.active) {
console.log('Service worker active');
}
}).catch(function(error) {
// registration failed
console.log('Registration failed with ' + error);
});
}
// function for loading each image via XHR
function imgLoad(imgJSON) {
// return a promise for an image loading
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', imgJSON.url);
request.responseType = 'blob';
request.onload = function() {
if (request.status == 200) {
var arrayResponse = [];
arrayResponse[0] = request.response;
arrayResponse[1] = imgJSON;
resolve(arrayResponse);
} else {
reject(Error('Image didn\'t load successfully; error code:' + request.statusText));
}
};
request.onerror = function() {
reject(Error('There was a network error.'));
};
// Send the request
request.send();
});
}
var imgSection = document.querySelector('section');
window.onload = function() {
// load each set of image, alt text, name and caption
for(var i = 0; i<=Gallery.images.length-1; i++) {
imgLoad(Gallery.images[i]).then(function(arrayResponse) {
var myImage = document.createElement('img');
var myFigure = document.createElement('figure');
var myCaption = document.createElement('caption');
var imageURL = window.URL.createObjectURL(arrayResponse[0]);
myImage.src = imageURL;
myImage.setAttribute('alt', arrayResponse[1].alt);
myCaption.innerHTML = '<strong>' + arrayResponse[1].name + '</strong>: Taken by ' + arrayResponse[1].credit;
imgSection.appendChild(myFigure);
myFigure.appendChild(myImage);
myFigure.appendChild(myCaption);
}, function(Error) {
console.log(Error);
});
}
};
You might be wondering, Application Cache is better.....
Here's an article to change your mind.
Service Worker
By Supriya kotturu
Service Worker
- 55