Matt Diamond
Matt Diamond

Reputation: 11696

Javascript not resolving worker path relative to current script

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?

Upvotes: 23

Views: 13935

Answers (4)

Klesun
Klesun

Reputation: 13719

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 to the worker script rather than the 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.

Upvotes: 3

JHT
JHT

Reputation: 112

With import.meta.url, you should be able to have it work like relative path.

var worker = new Worker(new URL('./fooWorker.js', import.meta.url));

Upvotes: 4

Justin
Justin

Reputation: 1120

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')

Upvotes: 4

Ilia Frenkel
Ilia Frenkel

Reputation: 1977

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.

Upvotes: 10

Related Questions