{"id":15277,"date":"2023-02-22T12:23:26","date_gmt":"2023-02-22T10:23:26","guid":{"rendered":"https:\/\/web-mate.gr\/what-are-service-workers\/"},"modified":"2023-02-22T12:23:26","modified_gmt":"2023-02-22T10:23:26","slug":"what-are-service-workers","status":"publish","type":"post","link":"https:\/\/web-mate.gr\/en\/what-are-service-workers\/","title":{"rendered":"Service Workers"},"content":{"rendered":"<h2>What service workers are and where they are used<\/h2>\n<p>We used to get push notifications only on our mobile phones; with the help of service workers we now get them on our computers too! But what are service workers? Put simply, a service worker is a script that runs in the background, and the user does not need to do anything for it to run. Service workers are used for caching files (e.g. CSS), push notifications and geofencing.<\/p>\n<p>The main drawback of service workers, if we can call it a drawback, is that they only work over secure HTTPS connections. That said, while building them we can work in a localhost environment, which makes life much easier.<\/p>\n<p>A tool that will help us further on: if we go to <code class=\" language-undefined\">chrome:\/\/serviceworker-internals<\/code> in Chrome, we will see all the service workers on our page.<\/p>\n<h2>Service Worker Example<\/h2>\n<p>Below is an example of how we first check whether our browser supports service workers, and then register one; if it is not supported, we say so in the console. The service worker lives in the file service-worker.js. With then we simply say what should happen once the service worker has been registered, and with catch we send the error to the console. To clear one thing up: if a user visits our page 10 times, the register function will run each time, but the browser decides whether it actually needs to do anything, depending on whether the service worker has already been registered.<\/p>\n<p><code><br \/>\n\/\/make sure that Service Workers are supported.<br \/>\nif (navigator.serviceWorker) {<br \/>\nnavigator.serviceWorker.register('.\/service-worker.js', {scope: '.\/about'})<br \/>\n.then(function (registration) {<br \/>\nconsole.log(registration);<br \/>\n})<br \/>\n.catch(function (e) {<br \/>\nconsole.error(e);<br \/>\n})<br \/>\n} else {<br \/>\nconsole.log('Service Worker is not supported in this browser.');<br \/>\n}<br \/>\n<\/code><\/p>\n<h2>Step 2: Creating variables for the files we want to cache<\/h2>\n<p>Now that we have told the browser to register the file, we also need to install the service worker and create variables for the files we want to cache, so that later on our website or app does not need an internet connection (by this we mean that the connection may be unreliable). So below we list which images and files should be cached. The CACHE_NAME variable is the name of the cache where our cached files will be stored from now on.<br \/>\n<code><br \/>\nvar CACHE_NAME = 'dependencies-cache';<br \/>\n\/\/ Files required to make this app work offline<br \/>\nvar REQUIRED_FILES = [<br \/>\n'random-1.png',<br \/>\n'random-2.png',<br \/>\n'random-3.png',<br \/>\n'random-4.png',<br \/>\n'random-5.png',<br \/>\n'random-6.png',<br \/>\n'style.css',<br \/>\n'index.html',<br \/>\n'\/', \/\/ Separate URL than index.html!<br \/>\n'index.js',<br \/>\n'app.js'<br \/>\n];<br \/>\n<\/code><\/p>\n<p>So we move on to the next step, which is the caching itself. What we do is install the service worker and use waitUntil() to wait for the CACHE_NAME cache to open and for all our files to be cached; after that, everything is in the cache.<\/p>\n<p><code><br \/>\nself.addEventListener('install', function(event) {<br \/>\n\/\/ Perform install step: loading each required file into cache<br \/>\nevent.waitUntil(<br \/>\ncaches.open(CACHE_NAME)<br \/>\n.then(function(cache) {<br \/>\n\/\/ Add all offline dependencies to the cache<br \/>\nreturn cache.addAll(REQUIRED_FILES);<br \/>\n})<br \/>\n.then(function() {<br \/>\n\/\/ At this point everything has been cached<br \/>\nreturn self.skipWaiting();<br \/>\n})<br \/>\n);<br \/>\n});<br \/>\n<\/code><\/p>\n<h3>Step 3: Once everything is cached, we can do whatever we like!<\/h3>\n<p>With everything cached in the previous step, we can now do whatever we like, even give the browser different content from what was actually requested (we won&#8217;t do that here). So with the fetch listener (a routine that runs whenever our page requests something, e.g. when something on our page is reloaded) we check what has been cached: if it hasn&#8217;t been cached we can serve it live, and if it has been cached we pull it from the cache. In our example, if everything has gone well, the content of our page will be available offline too, with no connection, as long as everything has been cached.<\/p>\n<p><code><br \/>\nself.addEventListener('fetch', function(event) {<br \/>\nevent.respondWith(<br \/>\ncaches.match(event.request)<br \/>\n.then(function(response) {<br \/>\n\/\/ Cache hit - return the response from the cached version<br \/>\nif (response) {<br \/>\nreturn response;<br \/>\n}<br \/>\n\/\/ Not in cache - return the result from the live server<br \/>\n\/\/ `fetch` is essentially a \"fallback\"<br \/>\nreturn fetch(event.request);<br \/>\n}<br \/>\n)<br \/>\n);<br \/>\n});<br \/>\n<\/code><\/p>\n<h2>The End!<\/h2>\n<p>There is a lot more we could do, for example check whether there was a previous service worker that we want to replace. See the code below:<br \/>\n<code><br \/>\nself.addEventListener('activate', function(event) {<br \/>\n\/\/ Calling claim() to force a \"controllerchange\" event on navigator.serviceWorker<br \/>\nevent.waitUntil(self.clients.claim());<br \/>\n});<br \/>\n<\/code><\/p>\n<p>What we have described above is a basis for starting to work with service workers and understanding how they can help you. It is a starting guide, and you will need to build on it before using it in a real project.<\/p>\n<p>If you would like more clarification, leave a comment in the form below!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What service workers are and where they are used We used to get push notifications only on our mobile phones; with the help of service workers we now get them on our computers too! But what are service workers? Put simply, a service worker is a script that runs in the background, and the user [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":9443,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","rank_math_title":"What Are Service Workers? A Beginner Guide | WebMate","rank_math_description":"What service workers are, what they are used for and how to register one, cache files and serve your pages offline, with JavaScript code samples.","rank_math_focus_keyword":"what are service workers"},"categories":[248],"tags":[],"class_list":["post-15277","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-website-programming"],"_links":{"self":[{"href":"https:\/\/web-mate.gr\/en\/wp-json\/wp\/v2\/posts\/15277","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/web-mate.gr\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/web-mate.gr\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/web-mate.gr\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/web-mate.gr\/en\/wp-json\/wp\/v2\/comments?post=15277"}],"version-history":[{"count":0,"href":"https:\/\/web-mate.gr\/en\/wp-json\/wp\/v2\/posts\/15277\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/web-mate.gr\/en\/wp-json\/wp\/v2\/media\/9443"}],"wp:attachment":[{"href":"https:\/\/web-mate.gr\/en\/wp-json\/wp\/v2\/media?parent=15277"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/web-mate.gr\/en\/wp-json\/wp\/v2\/categories?post=15277"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/web-mate.gr\/en\/wp-json\/wp\/v2\/tags?post=15277"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}