Do not store start_url in the service worker cache

I'm facing some challenges while trying to set up a service worker for my website.

My goal is to only cache css/js/fonts and specific images/svg files, without caching the HTML since it's constantly being updated every minute.

Although it seems to be partially working, I encountered issues when testing on my smartphone where I continuously receive the "Add to homescreen" notification even after adding it. Additionally, the Add button is not appearing in the Chrome Dev app.

Furthermore, Lighthouse has identified the following errors:

"Does not respond with a 200 when offline"

"User will not be prompted to Install the Web App, Failures: Manifest start_url is not cached by a Service Worker."

Currently, my sw.js file looks like this. I have commented out the fetch part as it was caching the HTML and causing issues with Cookies.

Is there a simple Service Worker template available that I can utilize?

const PRECACHE = 'app-name';
const RUNTIME = 'runtime';

// List of local resources to always be cached.
const PRECACHE_URLS = [
'/css/file.css',
'/js/file.js',
'/images/logo.png',
'/fonts/roboto/Roboto-Regular.woff2'
]

// Install handler for precaching necessary resources.
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(PRECACHE)
      .then(cache => cache.addAll(PRECACHE_URLS))
      .then(self.skipWaiting())
  );
});

// Activate handler for cleaning up old caches.
self.addEventListener('activate', event => {
  const currentCaches = [PRECACHE, RUNTIME];
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
    }).then(cachesToDelete => {
      return Promise.all(cachesToDelete.map(cacheToDelete => {
        return caches.delete(cacheToDelete);
      }));
    }).then(() => self.clients.claim())
  );
});

Answer №1

It seems that the unexpected appearance of the install banner could be related to the missing caching of the initial start_url, likely index.html. This is also causing Lighthouse to report two errors consistently. By implementing a proper caching strategy like the one you mentioned, these issues should be resolved.

One alternative approach you might consider is utilizing Workbox and their runtime caching feature. With runtime caching, specific URLs such as *.svg, *.css can be cached by the service worker upon client request. Subsequently, the SW will serve these files from cache when they are already stored, without pre-caching all resources upfront. Essentially, you instruct the SW to cache certain types of URLs as it encounters them.

Additionally, complementing runtime caching with precaching (also available through Workbox) can help in caching multiple files at once for faster loading times.

For more information and examples, visit:

Workbox provides various examples and plugins designed for improving build tool workflow.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Swap the image source with a different image attribute when making the website responsive

I have implemented a custom attribute for the img tag in my code, such as data-tablet and data-mobil <div class="myDiv"> <img src="img-1.jpg" data-tablet="img-2.jpg" data-mobil="img-3.jpg"> </div> My goal is to have the image source c ...

Current target in Internet Explorer 10 with Javascript

Encountering a problem with event.currentTarget in IE 10. Two divs are present on the website. The first div contains an image that takes up the entire screen, while the second div is smaller and positioned over the first div. The smaller div has no conte ...

Instructions for retrieving data from a weather API using JavaScript

Hello amazing Stackoverflow community! I need your help to figure out how to extract data from a weather REST API using JavaScript. I'm struggling to fetch the weather condition and date/time information from this API. { info: { _postman_i ...

Angular.js: Ensure all services are loaded before initializing the application

I am currently developing an application using angular.js and I need to ensure that the result from a specific service is accessible throughout the entire application right from the beginning. How can this be accomplished? The service in question is as f ...

What is the process for changing the behavior when the checkbox is selected or deselected?

Hello everyone. I'm facing a challenge that I can't seem to overcome. I'm trying to adjust the behavior of an element using the ".on/.off" methods based on whether a checkbox is ticked or not. Can someone provide some guidance on how to achi ...

Display map.svg on the browser and execute a function when any area is clicked

Creating an online parking system that is compatible with desktop, iPad, and Android devices is my current project. I have a .svg formatted map for the parking area. I am looking for advice on how to display this map in a browser and execute JavaScript fu ...

Navigating the maze of Express.js routes

When attempting to use sendFile to call my index.html page, I encountered a problem. The issue is that the index.html page displays without any of the CSS or JS/jQuery effects applied. This is what my server.js file looks like: var express = require("exp ...

Buttons to maximize, minimize, and close individual sections on a webpage

I am fairly new to front end development and I must say, I am absolutely enjoying every bit of it. Here is a little challenge that came my way. It may seem simple to some but it got me thinking. I have three sections on the right side of my website. I wa ...

What is the best way to transfer a string to a different Vue component?

Within my project, I have a masterData.js file that serves as a repository for my master data. This file retrieves data from my mongo db and distributes it to various components of the project. To facilitate this process, I have implemented a function with ...

What is the most efficient way to include multiple JavaScript functions without requiring document.ready() for each individual function?

I currently have functional code that looks like this: $(document).ready(function() { $("#num1").click(function() { $("li.elementsA").addClass("alerty"); return false }); }); $(document).ready(function() { $("#num2").click(function() { $(" ...

What is the reason for the Express middleware using parenthesis syntax, whereas custom-made middleware does not?

What is the reason behind Express inbuilt middleware using a parenthesis syntax like app.use(express.json()) while custom-made middleware does not use parentheses like app.use(logger)? It seems to throw an error with parentheses. I'm uncertain if th ...

Show and hide a division based on the status of a checkbox

I have a specific requirement regarding authentication modes. When selecting a single factor, only one type of authentication mode can be chosen at a time and the corresponding div will be displayed. However, when selecting multiple factors, I should be ab ...

Error: JSON parsing error encountered for token < at position 0 within the context of Google Sheets Apps Script Tutorial

I'm currently working through a Google Sheets Apps Scripts editor tutorial and I've reached module 4. Unfortunately, I've encountered an issue with the code I copied directly from the module. The error message I'm seeing is: SyntaxError ...

Retrieving information from a JSON file using JavaScript

My code snippet looks like this: { "badge_sets":{ "1979-revolution_1":{ "versions":{ "1":{ "image_url":"https://static-cdn.jtvnw.net/badges/v1/7833bb6e-d20d-48ff-a58d-67f ...

Clicking changes the texture and automatically hides other objects

I have a sphere in my scene and I want to change its texture when a click event occurs. However, when I apply the new texture to the sphere using my current code, it rearranges the elements in the scene causing other objects to be hidden behind the sphere. ...

The order of items in MongoDB can be maintained when using the $in operator by integrating Async

It's common knowledge that using {$in: {_id: []}} in MongoDB doesn't maintain order. To address this issue, I am considering utilizing Async.js. Let's consider an example: const ids = [3,1,2]; // Initial ids retrieved from aggregation con ...

What could be causing me to receive two builds when using Webpack?

I am trying to capture the hash of the build by using a callback function in webpack: const compiler = webpack(webpackConfig, function (err, stats) { debug("Hash", stats.hash) }) However, I am encountering an issue where two builds are generated and on ...

Loading React.js components before data fetch is complete

My app is encountering an issue where it renders before the fetch operation is completed, resulting in incorrect rendering. Below is the code snippet: componentWillMount() { fetch('http://localhost:8081/milltime/login?users='+this.state.e ...

What causes the variance in outcomes between employing a literal string versus a local variable?

Here is a loop that I am working with: for (var key in criteria) { var exists = Object.keys(item).some(function(k) { return item[k] === "Test"; }) } Initially, this loop functions as expected and returns 15 trues based on the number of i ...

Using React.useMemo does not efficiently avoid unnecessary re-renders

In my code, I am working with a simple component as shown below: const Dashboard = () => { const [{ data, loading, hasError, errors }] = useApiCall(true) if (hasError) { return null } return ( <Fragment> <ActivityFeedTi ...