Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/)?

like image 370
Ionică Bizău Avatar asked Oct 22 '25 11:10

Ionică Bizău


1 Answers

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! :)

like image 186
Praveen Kumar Purushothaman Avatar answered Oct 25 '25 01:10

Praveen Kumar Purushothaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!