The service worker is sending out a pair of requests

I have successfully set up a service worker to cache all requests for offline use, but I am experiencing a problem. Every time I load a page, two requests are hitting my webserver: one from the service worker and one from the browser!

How can I cache the request and only load the page once?

This is the code for my service-worker.js file:

self.addEventListener('install', function(event) {
  // Load error page which will show if user has no internet
  var errorPage = new Request('/?p=error&offline');
  event.waitUntil(pushToCache(errorPage));
});

// If any fetch fails, it will look for the request in the cache and serve it from there first
self.addEventListener('fetch', function(event) {
  event.waitUntil(pushToCache(event.request));

  event.respondWith(
    fetch(event.request) // Try loading from internet
    .catch(function (error) {
      return fetchFromCache(event.request);
    }) // No internet connection, try getting it from cache
  );
});

function pushToCache(request){
  if(request.method == "GET"){
    return caches.open('stm-app').then(function (cache) {
      return fetch(request).then(function (response) {
        return cache.put(request, response);
      });
    });
  }
};

function fetchFromCache(request) {
  return caches.open('stm-app').then(function (cache) {
    return cache.match(request).then(function (matching) {
      if(!matching || matching.status == 404){
        return fetchFromCache(new Request('/?p=error&offline')); // Show page that user is offline
      }else{
        return matching;
      }
    });
  });
}

And this is the content of my sw-register.js file:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('service-worker.js')
  .then(function(registration) {
    console.log('Registered:', registration);
  })
  .catch(function(error) {
    console.log('Registration failed: ', error);
  });
}

Answer №1

When a request is made, a series of events unfold:

  1. The webpage initiates a fetch request to the server,
  2. The Service Worker steps in and intercepts the request during the 'fetch' event,
  3. pushToCache() sends a fetch request to the server to store the response in the cache,
  4. Then you respond to the event with another fetch request to the server, which will generate a Promise for a Response from the web server.

Essentially, two requests are sent to the server for every initial request made by the page.

Consider prioritizing responding from the cache first before resorting to network requests for the most current data. This approach can prevent loading delays due to connectivity issues and improve overall page load times even when online.

Imagine this scenario: Either the user or server goes offline. When a request is fired, it must time out before triggering the catch part of the promise and fetching the cached response.

Upon intercepting the event, check the caches for a match. If found, respond with that data. Then proceed with a fetch request to update the cache. If no match is found, initiate a fetch request, clone the response (as the body can only be used once), reply with the original response, and update the cache with the cloned response.

What's the benefit of this process?

The user receives an immediate response regardless of their connection status—online, offline, or on Lie-Fi!

Additionally, the server deals with a single request at most while ensuring caches stay up-to-date with the latest server data!

For more insights on Service Workers and advanced functionalities, explore serviceworke.rs.

To delve deeper into implementing caching strategies, visit this specific page for detailed explanations on the aforementioned methodology.

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

Guide on transforming a JSON string into an array of custom objects using the json2typescript NPM module within a TypeScript environment

I am looking to utilize the json2typescript NPM module to convert a JSON string into an array of custom objects. Below is the code I have written. export class CustomObject { constructor(private property1: string, private property2: string, private p ...

Learn how to retrieve the value of an associated field at a specific index by utilizing a combo box in JavaScript when receiving a JSON response

Hey there, I'm currently working on a phone-gap app where I need to fetch data from a WCF service that returns JSON responses. Specifically, I want to display the DesignName in a combo box and pass the associated designId. Any thoughts on how I can ac ...

Utilize Node.js driver to export a Mongo collection into a JSON file

How can I export a MongoDB collection to a JSON format using the Node.js driver and fs.writeFile? ...

Generate various shapes using a loop

Hello, I'm currently working on creating multiple forms using a loop that is generated from dynamic elements fetched from the database. However, I believe there might be some issues in my approach. Below is what I have tried so far. While it works to ...

We encountered a surprise issue: "/Users/username/package.json: Unexpected character \ in JSON at index 1" – this is not a duplicate question

While running the yarn command in various projects, I encountered the same error consistently. Error message: "An unexpected error occurred: "/Users/name/package.json: Unexpected token \ in JSON at position 1". Trace: SyntaxError: /Users/name/pack ...

Is it possible to create a looped GLTF animation in three.js using random time intervals?

I am currently exploring the world of game development with Three.js and have a specific query regarding animating a GLTF model. Is it possible to animate the model at random intervals instead of in a continuous loop? In the game I am creating, players wil ...

developing a fresh node within the jstree framework

Recently, I have been working on creating a node using crrm as shown below $("#TreeDiv").jstree("create", $("#somenode"), "inside", { "data":"new_node" }); This specific function is triggered by a wizard, enabling me to seamlessly create a new node withi ...

Database entry does not appear in Internet Explorer until the browser is completely shut down and reopened

Currently, I have a form with two dropdowns. Selecting an option from the first dropdown automatically populates the second dropdown. Everything works well except for a minor issue I observed recently. When I add a new item to the second dropdown, it gets ...

Extensive data entry command

I need to add around 12500 lines to my database for a game server map. This script helps me generate the query: sql = "INSERT INTO `legends`.`map` (`x`, `y`, `land`, `collision`, `impedance`, `effect`) VALUES " for (y=0;y<ig.game.collisionMap.data.leng ...

ajaxStart - Display change inconsistency

These are some helpful comments to shorten and improve the readability of the code In my current project, I am using Javascript (Ajax) along with PHP (Laravel). I encountered an issue where I have set up two listeners in my ajax function. One listener is ...

Deleting the initial line in a JSON reply

My current code is : $.getJSON("https://www.domain.com/someapi/callback=?", function(data){ $.each(data, function(i,item){ alert(item.x); }); }); I am currently facing an issue with my JSON response because there is ...

Retrieve the size of an element without having to wait for the browser to "recalculate style"

I am currently focused on optimizing the performance of some code that heavily relies on graphics. One of the main issues I am encountering is the delay in obtaining the dimensions of a specific div element. Most of the time, this process runs smoothly, bu ...

Latest Information Regarding Mongodb Aggregate Operations

Struggling to toggle a boolean value within an object that is part of a subdocument in an array. Finding it difficult to update a specific object within the array. Document: "_id" : ObjectId("54afaabd88694dc019d3b628") "Invitation" : [ { "__ ...

Guide to crafting a reply using nestjs exception filters with nestfastify

I'm facing a challenge with writing custom HTTP responses from NestJS exception filters. Currently, I am using the Nest Fastify framework instead of Express. I have created custom exception filters to handle UserNotFoundException in the following mann ...

Even though `return false` is called, the line of code is still being executed

I am looking for a way to validate user input details before submitting them to the database. I have multiple tabs in a form and one common save button that triggers a save function when clicked, as shown below; $scope.saveFn = function () { $("#activ ...

What is the best way to connect data so that when a user clicks on a specific card, it appears on a popup card

When a user clicks on any card containing data retrieved from a backend API GET method, that data should be displayed in a pop-up card. In my situation, I have two components: DisplayNotes.vue and UpdateNotes.vue. Whenever a user clicks on a displayed card ...

The data visualization tool Highchart is struggling to load

As I try to integrate highcharts into my website, I encounter an unexpected error stating TypeError: $(...).highcharts is not a function. Below is the code snippet in question: @scripts = {<script src="@routes.Assets.at("javascripts/tracknplan.js")" ty ...

Sorting technique failing to reorganize list

I'm currently troubleshooting why my sorting function is not functioning as expected. My goal is for it to operate similarly to this example: https://codepen.io/levit/pen/abmXgBR The data I am working with is retrieved from an API: <BookCard v-fo ...

Transform JavaScript AJAX to HttpWebRequest implementation code

Is it possible to mimic an AJAX call to a web service within a console application using HttpWebRequest? Here is the source request: var webRequest = Sys.Net.WebServiceProxy.invoke('', 'MyMethod', false, {p1:aa,p2:bb,p3:123}, onSucc ...

An assortment of the most similar values from a pair of arrays

I am seeking an algorithm optimization for solving a specific problem that may be challenging to explain. My focus is not on speed or performance, but rather on simplicity and readability of the code. I wonder if someone has a more elegant solution than mi ...