21
votes

I have a script at http://localhost/js/foo.js which needs to spawn a Web Worker from the file http://localhost/js/fooWorker.js. I assumed I could just do something like this:

var worker = new Worker('fooWorker.js')

However, this results in a 404 error, as the browser cannot find http://localhost/fooWorker.js. I was under the impression that worker paths were resolved relative to the script spawning the worker, so shouldn't I just be able to specify the name of another .js file in the same directory without having to provide an absolute path? Am I doing something wrong?

3
According to developer.mozilla.org/en-US/docs/DOM/… , this should work...ziesemer
@ziesemer: The link you provided talks about sub-workers. These are not fully supported yet.Ilia Frenkel

3 Answers

8
votes

From http://www.w3.org/TR/workers/:

When the Worker(scriptURL) constructor is invoked, the user agent must run the following steps:

  1. Resolve the scriptURL argument relative to the entry script's base URL, when the method is invoked.
3
votes

Actually, it should be relative to the embedded document path

For example,

I have

pathDoc\docA.html
js\b.js
js\worker\c.js

then code should be

var worker = new Worker('..\js\worker\c.js')
1
votes

Note, you can still get the script url within the worker using the self.location and just prepend it to the paths to make them relative from the worker script rather than html base url.

const workerUrl = location + '';
const basePath = workerUrl.replace(/\/[^/]+$/, '/');

self.importScripts(basePath + '/fooWorker.js');

Btw, if you include your worker via blob, you can still pass meta info like it's url via # hash params.