Why can't Web Worker call a function directly?

前端 未结 7 1056
借酒劲吻你
借酒劲吻你 2021-02-01 03:15

We can use the web worker in HTML5 like this:

var worker = new Worker(\'worker.js\');

but why can\'t we call a function like this?



        
7条回答
  •  遇见更好的自我
    2021-02-01 03:35

    While it's not optimal and it's been mentioned in the comments, an external file is not needed if your browser supports blobURLs for Web Workers. HTML5Rocks was the inspiration for my code:

    function sample(e)
    {
        postMessage(sample_dependency());
    }
    
    function sample_dependency()
    {
        return "BlobURLs rock!";
    }
    
    var blob = new Blob(["onmessage = " + sample + "\n" + sample_dependency]);
    var blobURL = window.URL.createObjectURL(blob);
    var worker = new Worker(blobURL);
    
    worker.onmessage = function(e)
    {
        console.log(e.data);
    };
    
    worker.postMessage("");
    

    Caveats:

    • The blob workers will not successfully use relative URLs. HTML5Rocks link covers this but it was not part of the original question.

    • People have reported problems using Blob URLs with Web Workers. I've tried it with IE11 (whatever shipped with FCU), MS Edge 41.16299 (Fall Creator's Update), Firefox 57, and Chrome 62. No clue as to Safari support. The ones I've tested have worked.

    • Note that "sample" and "sample_dependency" references in the Blob constructor call implicitly call Function.prototype.toString() as sample.toString() and sample_dependency.toString(), which is very different than calling toString(sample) and toString(sample_dependency).

    Posted this because it's the first stackoverflow that came up when searching for how to use Web Workers without requesting an additional file.

    Took a look at Zevero's answer and the code in his repo appears similar. If you prefer a clean wrapper, this is approximately what his code does.

    Lastly -- I'm a noob here so any/all corrections are appreciated.

提交回复
热议问题