1

In my service worker file, I am using this code:

importScripts("https://storage.googleapis.com/workbox-cdn/releases/3.0.0-beta.2/workbox-sw.js");
const workbox = new WorkboxSW();

But I am getting error Uncaught ReferenceError: WorkboxSW is not defined hence my service worker is not registering.

abielita
  • 12,126
  • 2
  • 15
  • 52
Amit Singh
  • 1,700
  • 2
  • 12
  • 25
  • Based from this [thread](https://stackoverflow.com/questions/14500091/uncaught-referenceerror-importscripts-is-not-defined), when you create a worker it is actually executed twice. The first pass is in the context of the global `window` object(meaning you have access to all the window object functions). The second call through is in the context of the worker which has a different global object, one where `importScripts` exists. You may want to check this [documentation](https://www.html5rocks.com/en/tutorials/workers/basics/#toc-gettingstarted) for reference. – abielita Mar 13 '18 at 16:25

1 Answers1

4

In Workbox v3, you won't normally explicitly construct a WorkboxSW instance. Instead, there's a workbox variable exposed in the global scope that provides the interface to the library.

Here's an example, excepted from the migration guide:

Previously in v2:

importScripts('<path to workbox-sw>/importScripts/workbox-sw.prod.v2.1.3.js');

const workbox = new WorkboxSW({
  skipWaiting: true,
  clientsClaim: true,
  // etc.
});

workbox.router.registerRoute(...);

In v3, you just have to import the workbox-sw.js script, and a ready-to-use instance will be automatically available in the global namespace as workbox:

importScripts('<path to workbox-sw>/3.0.0/workbox-sw.js');

// workbox is implicitly created and ready for use.
workbox.routing.registerRoute(...);
Jeff Posnick
  • 45,379
  • 12
  • 113
  • 142