Console error: importScripts is not defined

I’ve been noticing this issue multiple times on some apps that accidentally run service-worker.js file in window scope - for example, some Vue Storefront based apps run it twice - on both window and worker scope:


which works fine but still gives the error what becomes confusing in result.

I’m thinking if Layer0 could just warn that service-worker.js file runs in a wrong scope?
Something like this can be added at the top:

// check if service-worker is running in the right scope
if (typeof importScripts !== 'function') {
  console.warn(`You're trying to run service-worker.js file on non-worker scope. Please check your framework build and make sure you're running your service worker file once on WorkerGlobalScope.`);
  return;
}

Or even maybe it’s worth to make it as a strict check and throw an error? Basically it already does it now, but it’s unclear for the most developers of what exactly going on, so that way we can make it more clear.

Thanks!

@egor.mesyats Are you referring to VSF 1 or 2?

@mark.brocato VSF 1: https://layer0-docs-layer0-vue-storefront-example-default.layer0.link/

@egor.mesyats While a warning message might help and is under consideration, the root cause is that the service worker is being imported into the wrong scope which you correctly identified. Can you help us understand what was/is your fix for that?

The service worker is imported via two different mechanisms in the Vue Storefront demo:

  1. register() which correctly signals to the browser to execute the service worker in a service worker context.

  2. Embedded as a standard <script> element in a comment-partitioned area in the document head (search for “<!-- layer0 -->” in the index.html file), alongside other embedded scripts which appear to have been inserted by the Layer0 build tool.

I was not able to confirm if the build tool actually inserts those specific scripts. There are undeclared dependencies in one or more of the Layer0 libraries which causes builds to fail for the setup described in the documentation.