Skip to main content

How to avoid importScripts is not defined in React

Kevin Basset avatar
Written by Kevin Basset
Updated over 4 months ago

If you attempt to initialize Progressier's default service worker into your React project, you may encounter the following issue when building your app with React:

importScripts is undefined

Why is importScripts undefined in React?

It's a matter of context. When the code of the worker is executed in the context of the actual service worker β€” where importScripts does indeed exist β€” everything will be fine. However, if you use React with ESLint or other code analysis programs, the existence of that function may be verified in a different context β€” one where importScripts doesn't exist.

How to fix importScripts is undefined in React

If you use ESLint, add the following line of code right before you invoke the importScripts function:

// eslint-disable-next-line no-undef

Alternatively, you could conditionally invoke importScripts after making sure importScripts is defined as follows:

if (typeof importScripts === "function") { 
importScripts("https://progressier.app/pW6HKX1b5pULMSOQCice/sw.js");
}

Example

This is the default Progressier service worker:
​

This is the amended version:

Did this answer your question?