Search code examples
htmlxmlhttprequestweb-worker

Web Worker loading of absolute URL


Can I load a web worker script from an absolute URL? - The answer over here is no.

However there is a hack I found to do it anyway:

var worker; //= new Worker('http://xyz/FSWorker.js');
var xhr = new XMLHttpRequest();
xhr.open("GET", 'http://xyz/FSWorker.js');
xhr.responseType = 'blob';
xhr.onload = function(e) {
    var blob = this.response;
    worker = new Worker(window.URL.createObjectURL(blob));
    fs_ready(); // do more stuff here
};

xhr.send(null);

I don't like this method that much - I now have to start using the worker only when an XHR is finished. The other option is to work with inline worker, but that's even uglier because then I'd have to put all my code into one huge string.

Is there any better way to do that?


Solution

  • You've discovered a clever feature of Web Workers -- you can create the from almost any arbitrary text blob.

    If you load the script as a <script> node on the current page you can use a similar Blob technique to create a Web Worker from it. As for loading remote scripts, your relying on XHR is as elegant as it gets to access the text contents of a remote script.