<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Manish on Medium]]></title>
        <description><![CDATA[Stories by Manish on Medium]]></description>
        <link>https://medium.com/@balyan_manish?source=rss-1fa40b27bd4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*wmYTdQjkonHahDokxHy4Rg.jpeg</url>
            <title>Stories by Manish on Medium</title>
            <link>https://medium.com/@balyan_manish?source=rss-1fa40b27bd4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 11:21:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@balyan_manish/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Service Workers and Caching Strategies(Part 1)]]></title>
            <link>https://medium.com/@balyan_manish/service-workers-and-caching-strategies-part-1-78d54960e8cd?source=rss-1fa40b27bd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/78d54960e8cd</guid>
            <category><![CDATA[service-worker]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Manish]]></dc:creator>
            <pubDate>Thu, 20 Feb 2020 15:11:41 GMT</pubDate>
            <atom:updated>2020-02-23T09:36:02.996Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Understand service workers and know when to use which caching strategy</blockquote><p><em>Part 1: Understand Service Worker</em></p><p><em>Part 2: Understand Caching Strategies</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I_zOr9mPgY72N8Z9" /><figcaption>Photo by <a href="https://unsplash.com/@casparrubin?utm_source=medium&amp;utm_medium=referral">Caspar Camille Rubin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Service Worker?</h3><p>A service worker is a script that your browser runs in the background, separate from a web page, and provides features like push notifications, background sync and rich offline experience that don’t need a web page or user interaction.</p><p>Service worker sits between the client and server and all the requests that are made to the server pass through the service worker so it is capable of intercept these requests on the fly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*6PdlM37QU6itgHHenbeAmA.png" /></figure><h3>Things to note about a service worker:</h3><ol><li>It’s a JavaScript Worker, so it can’t access the DOM directly. Instead, a service worker can communicate with the pages it controls by responding to messages sent via the <a href="https://html.spec.whatwg.org/multipage/workers.html#dom-worker-postmessage">postMessage</a> interface, and those pages can manipulate the DOM if needed.</li><li>It’s terminated when not in use, and restarted when it’s next needed, so you cannot rely on global state within a service worker’s onfetch and onmessage handlers. If there is information that you need to persist and reuse across restarts, service workers do have access to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API">IndexedDB API</a>.</li></ol><h3>Registering the service worker</h3><p>To install a service worker you need to kick start the process by <strong>registering</strong> it in your page. This tells the browser where your service worker JavaScript file lives.</p><pre>if (&#39;serviceWorker&#39; in navigator) {<br>  window.addEventListener(&#39;load&#39;, function() {<br>    navigator.serviceWorker.register(&#39;/sw.js&#39;).then(function(registration) {<br>      // Registration was successful<br>      console.log(&#39;ServiceWorker registration successful with scope: &#39;, registration.scope);<br>    }, function(err) {<br>      // registration failed :(<br>      console.log(&#39;ServiceWorker registration failed: &#39;, err);<br>    });<br>  });<br>}</pre><p>The above code checks to see if the service worker API is available, and if it is, the service worker at /sw.js is registered once the page is loaded.</p><p>You can call register() every time a page loads without concern; the browser will figure out if the service worker is already registered or not and handle it accordingly.</p><p>Now you can check that a service worker is enabled by going to chrome://inspect/#service-workers and look for your site.</p><h3>Life Cycle of Service Worker</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*HUnu3nbBSq2lDoOSllBkiA.png" /><figcaption>Service Worker life cycle</figcaption></figure><h3>Install a service worker</h3><p>After the registration process, let’s move on to the point of view of the service worker script, which handles the install event.</p><p>For the most basic example, you need to define a callback for the install event and decide which files you want to cache.</p><p>Inside of our install callback, we need to take the following steps:</p><ol><li>Open a cache.</li><li>Cache our files.</li><li>Confirm whether all the required assets are cached or not.</li></ol><pre>var CACHE_NAME = &#39;my-site-cache-v1&#39;;<br>var urlsToCache = [<br>  &#39;/&#39;,<br>  &#39;/styles/main.css&#39;,<br>  &#39;/script/main.js&#39;<br>];</pre><pre>self.addEventListener(&#39;install&#39;, function(event) {<br>  // Perform install steps<br>  event.waitUntil(<br>    caches.open(CACHE_NAME)<br>      .then(function(cache) {<br>        console.log(&#39;Opened cache&#39;);<br>        return cache.addAll(urlsToCache);<br>      })<br>  );<br>});</pre><p>Here you can see we call caches.open() with our desired cache name, after which we call cache.addAll() and pass in our array of files. This is a chain of promises (caches.open() and cache.addAll()). The event.waitUntil() method takes a promise and uses it to know how long installation takes, and whether it succeeded or not.</p><p>If any single file is not cached, then the service worker is not installed. So, it is important to make sure that there is not a long list of URLs to cache because if even a single url fails to cache, it will halt the installation of the service worker.</p><h3>Activate a Service Worker</h3><p>One common task that will occur in the activate callback is cache management. The reason you&#39;ll want to do this in the activate callback is because if you were to wipe out any old caches in the install step, any old service worker, which keeps control of all the current pages, will suddenly stop being able to serve files from that cache.</p><p>Let’s say we have one cache called &#39;my-site-cache-v1&#39;, and we find that we want to split this out into one cache for pages and one cache for blog posts. This means in the install step we&#39;d create two caches, &#39;pages-cache-v1&#39; and &#39;blog-posts-cache-v1&#39; and in the activate step we&#39;d want to delete our older &#39;my-site-cache-v1&#39;.</p><p>The following code would do this by looping through all of the caches in the service worker and deleting any caches that aren’t defined in the cache whitelist.</p><pre>self.addEventListener(&#39;activate&#39;, function(event) {</pre><pre>  var cacheWhitelist = [&#39;pages-cache-v1&#39;, &#39;blog-posts-cache-v1&#39;];</pre><pre>  event.waitUntil(<br>    caches.keys().then(function(cacheNames) {<br>      return Promise.all(<br>        cacheNames.map(function(cacheName) {<br>          if (cacheWhitelist.indexOf(cacheName) === -1) {<br>            return caches.delete(cacheName);<br>          }<br>        })<br>      );<br>    })<br>  );<br>});</pre><h3>Idle State of Service Worker</h3><p>After the activate stage the service worker sits idle and does nothing until another event is fired.</p><h3>Fetch State</h3><p>Now that you’ve <strong>installed and Activated </strong>a service worker, you probably want to return one of your cached responses, right?</p><p>the service worker will begin to receive fetch events, an example of which is below.</p><pre>self.addEventListener(&#39;fetch&#39;, function(event) {<br>  event.respondWith(<br>    caches.match(event.request)<br>      .then(function(response) {<br>        // Cache hit - return response<br>        if (response) {<br>          return response;<br>        }<br>        return fetch(event.request);<br>      }<br>    )<br>  );<br>});</pre><p>Here we’ve defined our fetch event and within event.respondWith(), we pass in a promise from caches.match(). This method looks at the request and finds any cached results from any of the caches your service worker created.</p><h3>Conclusion</h3><p>In this article, we learned about Service Workers . Hope you liked the article. Please click the 👏 button and share to help others find it! Thanks for reading 🙏 Please feel free to comment and ask anything.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78d54960e8cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>