简体   繁体   English

网络工作者内联而不是获取另一个页面

[英]web workers inline instead of fetching another page

I would like to create web workers in line instead of referencing an external script (so that I can deploy a single HTML page instead of an HTML file and a JS file). 我想在线创建Web Worker,而不是引用外部脚本(这样我可以部署单个HTML页面而不是HTML文件和JS文件)。 I found a cool method online using Blobs here , but for some reason I cannot get it to work. 我在这里使用Blobs 网上找到了一种很酷的方法,但是由于某种原因,我无法使其正常工作。 I noticed mixed results in the comments section of that article too. 我在该文章的评论部分也注意到了不同的结果。

I am getting an error: Failed to load resource: the server responded with a status of 404 (Not Found) which errors on line: localhost:63342/[object%20Worker]:1 我收到一个错误: Failed to load resource: the server responded with a status of 404 (Not Found) ,该错误在线: localhost:63342/[object%20Worker]:1

I'm guessing that the web worker isn't really the issue, it's in creating the temporary url resource? 我猜测网络工作者并不是真正的问题,而是在创建临时网址资源? If so what am I missing still? 如果是这样,我还缺少什么?

Here's my code, in the script tag in the HTML file: 这是我的代码,位于HTML文件的script标记中:

function createWorker(fn) {
    var blob = new Blob(['self.onmessage = ', fn.toString()], { type: 'text/javascript' });
    var url = window.URL.createObjectURL(blob);

    return new Worker(url);
}

var generic = function(e) {
    self.postMessage('in line web worker code');
};

var worker = createWorker(generic);

if (window.Worker) {
    var getEquipmentW = new Worker(worker);

    getEquipmentW.postMessage({
        msg: 'hi'
    });

    getEquipmentW.onmessage = function (e) {
        console.log(e.data);
    };
}

You function createWorker already returns a worker, so you can replace: 您的函数createWorker已经返回了一个工作程序,因此您可以替换:

var worker = createWorker(generic);
var getEquipmentW = new Worker(worker);

With this: 有了这个:

var getEquipmentW = createWorker(generic);

I'll answer my own question, you can include a Web Worker in a separate script tag. 我将回答我自己的问题,您可以在单独的script标签中包含Web Worker。 I believe the script type isn't an official one, so the code in this tag is not evaluated until later. 我认为该脚本类型不是官方的,因此该标记中的代码要到以后才进行评估。 It'll look something like this: 它看起来像这样:

<script id="myWorkerCode" type="javascript/worker">

self.onmessage = function(e) {
    const data = e.data
    self.postMessage('received some data in worker thread');
};
</script>

then, in the script where you need the worker, create a Blob and assign the content to be the "javascript" type. 然后,在需要工作人员的脚本中,创建一个Blob,并将内容分配为“ javascript”类型。 make that Blob be a URL that you can feed into the Worker constructor: 使Blob成为您可以输入到Worker构造函数中的URL:

if(window.Worker) {
            // select the id of the script that contains your worker code
            const blob = new Blob([
                document.querySelector('#myWebWorker').textContent
            ], {type: "text/javascript"})

            // Note: window.webkitURL.createObjectURL() in Chrome 10+.
            const worker = new Worker(window.URL.createObjectURL(blob));

            worker.onMessage = (e) => {
               console.log('received data in main thread')
            };
        }

It's more of a "in-a-line-above" than "inline", but it allows web workers to be composed and used in the same file. 它比“内联”更像是“上一行”,但是它允许Web Worker在同一文件中组合和使用。 The trick is using script tags and converting unevaluated javascript by assigning the script tags to the given types in the code above. 诀窍是使用脚本标记,并通过将脚本标记分配给上面代码中的给定类型来转换未评估的javascript。 Still not the most elegant solution, but very handy when pushing processes to another thread. 仍然不是最优雅的解决方案,但是在将进程推到另一个线程时非常方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM