Ionică Bizău
Ionică Bizău

Reputation: 113465

Does the Worker constructor accept relative urls?

I wonder if the Worker constructor from accept relative paths. For example, having a file structure like this:

root/
+---js/
|   +--workers/
|   |  +--some-worker.js
|   +--index.js
+---index.html

If index.html loads index.js and index.js does something like this:

var someWorker = new Worker("./workers/some-worker.js");

Will this work fine? Well, no. The strange thing is that it resolves the url to <domain>/workers/some-worker.js.

Is there a solution for this issue? I expected to load <domain>/js/workers/some-worker.js instead.

How to make new Worker("workers/some-worker.js") to resolve to the relative directory (in this example /js/workers/some-worker.js, since it was called from /js/)?

Upvotes: 4

Views: 2321

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167220

You cannot use relative URLs for this. The other thing is that, it accepts relative URLs as relative to the domain. So, it is either:

  • Absolute URLs
  • Relative URLs to Domain

Nothing other than these. You can refer MDN Worker() for more information.

Also you do have a workaround, by setting the URL by getting the current location. So you do this instead:

var someWorker = new Worker(location.href + "/workers/some-worker.js");

Or to be precise, you can do this:

currentPath = location.href.split("#");
if (currentPath.length > 1)
  currentPath = currentPath[0];
currentPath = location.href.split("?");
if (currentPath.length > 1)
  currentPath = currentPath[0];
var someWorker = new Worker(currentPath + "/workers/some-worker.js");

Hope this helps! :)

Upvotes: 4

Related Questions