A mysterious issue arose while trying to retrieve the script (Service Worker)

After disconnecting from the internet, my service worker is generating the following error:

(unknown) #3016 An unknown error occurred when fetching the script

This is what my service worker code looks like:

var version = 'v1'

this.addEventListener('install', function(event){
  event.waitUntil(
     caches.open(version).then(cache => {
       return cache.addAll([
         'https://fonts.googleapis.com/icon?family=Material+Icons',
         'https://fonts.googleapis.com/css?family=Open+Sans:400,600,300',
         './index.html'
       ])
     })
   )
})

this.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(resp) {
      // if it's not in the cache, server the regular network request. And save it to the cache
      return resp || fetch(event.request).then(function(response) {
        return caches.open(version).then(function(cache) {
          cache.put(event.request, response.clone())
          return response
        })
      })
    })
  )
})

The service worker file is located at the root directory, alongside a manifest that is imported in index.html like this:

<link rel="manifest" href="/manifest.json">

I import the service worker in my entry js file. And register it right after.

require('tether-manifest.json')
import serviceWorker from 'sw'

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register(serviceWorker)
  .then(() => {
    // registration worked
  }).catch(error => {
    throw new Error(error)
  })
}

The registration process goes smoothly, the error only occurs when going offline.

I am using webpack with React, and the following configuration is used to copy my sw.js file to the dist folder:

loaders: [
      { // Service worker
        test: /sw\.js$/,
        include: config.src,
        loader: 'file?name=[name].[ext]'
      },
      { // Manifest
        test: /manifest\.json$/,
        include: config.src,
        loader: 'file?name=[name].[ext]'
      }
]

The error message does not provide any insight into the cause of the issue.

Does anyone have suggestions on how to resolve this?

Answer №1

After struggling for an hour with a perplexing issue, I finally discovered that the culprit was a lingering additional tab from the same origin that had been left open. This tab had the "Offline" checkbox activated, preventing other tabs from requesting sw.js for some unknown reason.

Evidently, the offline status of one tab was affecting the Service Worker scope and not being properly managed by other tabs that were not initially put into Offline mode.

To avoid this issue, ensure that no other clients are utilizing the same Service Worker. You can check for them under DevTools > Application > Service Workers.

Answer №2

I was able to resolve this error by including sw.js in the cache during installation. It was a simple step that I had overlooked, but it successfully fixed the problem.

Answer №3

First and foremost, make sure to double-check if your https certificate is valid or matches the URL you are trying to access.

For example, in a scenario where I attempted to visit https://localhost using a certificate issued for a different domain.

Even though clicking "proceed" allowed me to proceed to the site, the following error message would be displayed in the console:

An unknown error occurred while fetching the script

Answer №4

During my time working on a project with Angular, I encountered a specific issue. The problem stemmed from my reliance on the ng serve -prod command offered by Angular CLI.

To resolve this issue, I switched to utilizing ng build -prod and subsequently deployed the resulting dist folder through an http-server.

Answer №5

When using Google Chrome, I solved the issue by selecting the Bypass for network option and then successfully reloading the page.

https://i.sstatic.net/1JNEH.png

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

What is the ideal approach for setting up the react-native CLI - local module or global installation

I've been following the initial steps to start with React Native from FB's git page at https://facebook.github.io/react-native/docs/getting-started While using nxp or npm installed CLI during the process, I encountered the following error. [!] ...

Loop through each div using jQuery and dynamically add or remove a class to

I am looking to create an infinite loop that adds a class to each div with a timeout in between. Currently, I have implemented it like this: $(document).ready(function() { $('.small-bordered-box').each(function(i) { var $t = $(this); ...

RTM is lacking dropdown navigation menus

In Visual Studio 2013 beta versions, there were dropdown menus at the top of the javascript editor that functioned similarly to those in c# and vb editing. Have these been removed from the RTM or final release, or are they available with a specific version ...

Converting EDN data to a string and back in Clojure/ClojureScript

When working with JavaScript, one can convert a JavaScript data structure into a JSON string using the following code: JSON.stringify({somedata: { somesubdata: {}}}) Then, to parse it back into a JS data structure, you can use: var my_obj = JSON.parse(" ...

Understanding how to bind data in JavaScript client-side templates

I've started incorporating Client Side templates into my JavaScript code. Currently, I'm using the $create method to bind a Sys.UI.DataView to my data. The "data" variable contains a JSON result with 100 records, all of which are being bound by ...

Error: The function seems to be malfunctioning or missing

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $('div'); // <--- THIS DOESN'T WORK </script> An issue has been encountere ...

What is the correct way to handle JSON responses with passport.js?

In my Express 4 API, I am using Passport.js for authentication. While most things are working fine, I have encountered difficulty in sending proper JSON responses such as error messages or objects with Passport. An example is the LocalStrategy used for log ...

What methods can be used to accurately display the data type with TypeOf()?

When working with the following code: const data = Observable.from([{name: 'Alice', age: 25}, {name: 'Bob', age: 35}]); console.log(typeof(data)); The type is displayed as Object(). Is there a way to obtain more specific information? ...

"Sequencing time with Postgres, manipulating views with Angular

I am encountering issues with displaying graphs in AngularJS. My backend is written in nodeJS and includes an aggregator as a buffer for data received from netdata, which is then inserted into the database using a cron job. Now, with a new client request, ...

Preventing User Duplication in MERN Stack: Strategies to Avoid Multiple Registrations

A developer fairly new to the field is working on a project using the MERN stack. Within this app, there are two models: one for Users and another for Tournaments. The Tournament model contains an attribute called participants, which is an array. The dev ...

JavaScript does not recognize Bootstrap classes

I am utilizing Bootstrap 5.3.0 and have included it through CDN links in my JS script. This is how I am injecting it using my js file within the existing website's DOM via a chrome extension named Scripty, which serves as a JS injector extension for c ...

Hide preloader in AngularJS once repeater has completed execution

Is there a way to hide a preloader div only after all data has finished loading in an ng-repeat loop? Check out this interactive example on Plunker: http://plnkr.co/edit/ilgOZzIy2axSi5Iy85C7?p=preview Here is the HTML code: <div ng-co ...

Error encountered while implementing onMutate function in React Query for Optimistic Updates

export const usePostApi = () => useMutation(['key'], (data: FormData) => api.postFilesImages({ requestBody: data })); Query Definition const { mutateAsync } = usePostApi(); const {data} = await mutateAsync(formData, { onMutate: ...

Is there a standard event triggered upon the closing of a browser tab or window?

Does React have a built-in event that is triggered when a browser tab or window is closed? If it does, does it have support across different browsers? ...

Enhancing the efficiency of nested ajax calls loop

Disclaimer: While the final result is successful, I am struggling to comprehend the sequence in which a loop of nested ajax calls operates. Essentially, I have two ajax calls that fetch data from an external API using curl GET requests. They both rely on ...

Passport.socket.io cannot resolve the issue of a missing session

The Issue I am facing a problem with the failed connection to socket.io: No session found using passport.socketio.js and I am unable to identify the root cause. Despite checking similar posts, the configuration seems fine to me. However, it appears that ...

none of the statements within the JavaScript function are being executed

Here is the code for a function called EVOLVE1: function EVOLVE1() { if(ATP >= evolveCost) { display('Your cell now has the ability to divide.'); display('Each new cell provides more ATP per respiration.'); ATP = ATP ...

How can I insert an HTML/PHP code snippet into a <ul> list using JavaScript?

My upload.php file saves images into an uploads/ folder within my main directory. I am looking to dynamically add a new li tag to my index file each time an image successfully uploads. Here is a snippet from index.php: <ul> <li><im ...

How can I stop Jquery Mobile from processing the URL hash?

Currently implementing Jquery Mobile in a preexisting web application is posing a challenge. The issue arises as Jquery Mobile is interpreting all URL hashes by default. For example: mysite.com/#foo In this case, the hash 'foo' is being directe ...

bring in all the files located within the Directory

Is there a way to import all CSS files from a specific folder without having to import each file individually? Looking to import assets/css/* ? <link href="<?php echo base_url(); ?>assets/css/*" rel="stylesheet"/> <title&g ...