Ever wondered why some sites loads slow when you first visit them, but after loading the full page when you get back the next time the site loads instantly fast, in today’s guide I will be walking you through the beauty of service worker by demonstrating how you can reduce you’re site loading time in the users browsing device the next time they visit you’re site.
Table of Contents
- Prerequisites
- What is a service Worker
- Caching
- Basic caching implementation using Service worker
- Starting Cache operations
- Wrap Up
- Final Thoughts
Prerequisites:
To follow along this guide, you must be familiar with the following JavaScript concept:
- Promises
- Events in JavaScript
What is a service Worker:
service workers is a JavaScript technique of running tasks in the background from the page main thread to help us developers, intercept request, cache resources from the client and even allows the app to run even offline, we will be focusing on how to cache resources/assets of the site in this article today.
Caching
caching is to save resources and assets of the site that takes too much time to load to the browser’s memory so the next time we try to access them we won’t need to re-download them from the server rather but on the browser's memory which is instantly first than getting them from the server.
Basic caching implementation using Service worker
I have a created a simple site of space tourism which contains information about different location on the space you can visit in the space and the details about it; is a frontend mentor challenge which you can find using this link if you want to try it out and follow along with.
this project is the perfect scenario to explain how we can cache the resources to reduce the load time on our site, and to be clear a site with a lot of visuals like images can be slow so I want to cache the home page to show how you can cache the site if you find site loading slowly and give you an insight on how service worker and caching works.
Looking at this image below, I am displaying all the time and size each file is taking to load the full homepage or index page
Image showing the network status when I first load the site on my device for the first time
You can see that I am fetching files with 264 KB in 266ms as the time it takes to load the whole landing page which means when I again visit the site it will take the same amount of time and size to load which is not ideal, again you find this information by going to the devtools→network tab
We start by registering a service worker in the app entry or main file mine is index.js
if("serviceWorker" in window.navigator){
window.navigator.serviceWorker.register('/sw.js').then(registeredSw => console.log(registeredSw).catch(err => console.log(err))
}
We start by checking if the current browser the app/site running on supports the service Worker, serviceWorker is a property of the navigator object of the windows object.
we use the register() on the serviceWorker to register a service worker in the browser, which takes in 2 arguments the first one is the destination where we’ve created a file which we will be writing in all our caching logic it is advised to put the service worker file in global directory in order to have access to all files
and the second argument is optional, the scope of files the service worker will track if you’ve saved it in a certain folder, it’s scope would be that given directory that why it advisable to put in the global directory.
The register() returns a Promise we use then to display the registered service worker and catch to catch any errors that may occur while registering the service worker
if it is successfully registered will be returned its instance in console which will look like this
The console shows the registered service worker
To view the created service worker, you will need to navigate to:
devtools- application and choose the Service workers pane on the left panel of the application section
service worker takes 3 phases it passes through to be installed which are:
- installation: which have completed in the first step when we register a new service worker
- Activation: activation of the service worker to start operating
- wait: Still waiting for the service to be activating
Starting Cache operations:
In service Workers we use event driven approach to cache and fetch our resources and assets; in this section we will look each one of events needed to start service worker and cache your assets and resources and explain its part in caching resources/assets.
install event:
Exploration of the event
this is the first event to be fired, remember when we registered a new service worker that’s when the event is triggered
in this event we create a cache storage in the browser and add the resources that we will need to be cached in the cache.
Implementation of the event
to implement switch to the sw.js you have registered as you're service worker file and then implement the following snippet
const resourcesToCache = [
"/",
"/index.html",
"src/JavaScript/index.js",
"src/output.css",
];
const cacheName = "version-1";
self.addEventListener("install", (event) => {
event.waitUntil(
caches
.open(cacheName)
.then((cache) => {
cache.addAll(resourcesToCache);
})
.catch((err) => console.log(err)),
);
});
The above snippet declare resourcesToCache array to keep track of multiple resources and assets we want to cache and cacheName is the name that will use as the cache name.
event setup:
- the
selfis service worker we have registered, essentially it is attaching event to itself that’s why they call itself - we attach an event of
installas well as a callback function that will trigger when service worker is first registered on any device browser our site/app is running in.
Cache setup:
- The
waitUntil()on the install event ensures that the service worker is installed after the operation inside thewaitUntil()has completed. - The
cachesobject helps create, manage the browser’s cache storage. - We start by opening a new cache with
open()which takes a string as an argument that will act as a cache name, we used thecacheNamevariable. - The
open()returns a promise we chainthen()to access the created cache. - The
.addAll()to add multiple resources we would like to cache and finally acatchblock to handle any errors that may occur in caching.
you’ve just cached you’re first assets/resources in your browser cache, to view the changes go to devtools(application→Service workers) and you should see you a button labeled as skipWaiting
Service worker panel in the browser
click on skipWaiting and then look on the left and then expand to Cache Storage tab you should see the name of you cache and when you click on it you will see resources cached insider there
created cache in the browser
and this should be it for setting up the cache for the site
NOTE: that to make testing easier it is better to enable the checkbox for Update on reload in service workers’ section; to test without needing to click on skipWaiting every single time you make changes to the page.
activate event:
Exploration of the event
this event fires every time there is a new change in a service worker file, its responsible is to activate a service worker.
Implementation of the event
self.addEventListener("activate", (event) => {
console.log("Activated service worker");
});
we use the activate event to trigger activation of our service worker every time there is a change in service worker file, so the next time you change something from the sw.js the activate event will be triggered and in console you will see the message ‘Activated service worker’.
Fetch event:
Exploration of the event:
This event is fired every time you make a request to the server requesting resources/assets, and this is where we intercept the request and first check if the data we are trying to download from the server includes in our cache if we have it in our cache we can directly return them if not we can continue with the request.
Implementation of the event:
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
}),
);
});
in above snippet we have:
- attached
fetchevent to service worker that will trigger any time we make a request - we access the
respondWith()of thefetchevent, therespondWith()method will help intercept the request before it sends to the server requesting some assets/ resources - we access the
requestproperty on theeventobject. - inside the
respondWith()we then usematch()and pass our request to find the matching resources/assets in cache similar to the request we are sending to the server. - the
caches.match()returns a promise, we attachthen()to handle the resolve the promise and if it has found some assets/resources in our cache we then return them instantly if not we continue with the request.
to see the effects of this let’s compare the network of the first image when we had no service worker and now, when we have a service worker
Figure A: Before service worker implementation network report
network request report of site with not service worker and cache
Figure B: After service worker implementation network report
network request report of site with service worker and cache
With this you can see the difference, the file that we are getting from our service worker have a low load time compared to before the service worker and you can see they are taking up 0 size compared to before.
before we had a load time of 266 and after service worker, we have a load time of 124 which is less than half of the first load time we had before we cache.
we also had 264Kb of our resource size before we apply service worker but now, we only have 116Kb of resource size.
Wrap Up
In this guide we covered how to apply cache to static resources that may cause long load time which can be a bad user experience on the site,
Final Thoughts
Service workers are not only limited to caching resources they can be used for push notifications, enabling site accessibility in offline mode which is commonly known as PWA (Progress web app)
This guide helps you get started working with service worker, basic implementation and fundamental explanation of how caching works, in future articles I am planning to dive deep of how we can use service worker not only for caching but also for offline accessibility and background sync techniques.







Top comments (0)