[Django]-Getting Failed to construct 'Worker' with JS worker file located on other domain

5πŸ‘

βœ…

For anyone reading this: I figured out what the problem is.

Most browsers don’t allow you to load a Worker from an external source, even if the CORS headers are all in order, the script loading is loaded from the same source as the worker, and the source is in my control.

Chrome, Firefox, and Safari all gave different errors, which was why I was confused as to what exactly happened.

The way I fixed this was by not loading the external worker, and running the code inline.

Two other ways to fix this are:

  • Serving the worker.js file from the same origin as the webpage.
  • Creating a worker through a blob URL (Like in this link).
    The worker I used was loaded from a package inside my dependencies, I tried to configure Webpack to load this worker like this, but I could not get it to work.

So in the end I opted for not loading the worker at all.

2πŸ‘

Support CROS worker with a blob URL, you can do like this:

function workerCros(url) {
  const iss = "importScripts('" + url + "');";
  return URL.createObjectURL(new Blob([iss]));
}

const workerUrl = workerCros(new URL(workerFilePath, window.location).href);
const worker = new Worker(workerUrl);

Leave a comment