简体   繁体   English

如何在Web Worker中使用其他库?

[英]How Can I use Other Libraries in a Web Worker?

I have some javascript code like this, 我有一些像这样的javascript代码,

var worker = new Worker("javascript/worker.js");

worker.onmessage = function(evt)
{
    // stuff
}

worker.js looks like this, worker.js看起来像这样,

importScripts("base.js");

function getImage()
{
    $.ajax({
    url: 'URL'
    dataType: "text/plain; charset=x-user-defined",
    mimeType: "text/plain; charset=x-user-defined",
    success: function(data, textStatus, jqXHR)
    {
        callback();
    }
});
}

The worker.js file does not have jQuery included so that doesn't work. worker.js文件没有包含jQuery,因此不起作用。 If I add this to worker.js, 如果我将它添加到worker.js,

importScripts("jQuery.js");

Then I get the message, 然后我收到消息,

Uncaught ReferenceError: window is not defined

I'm not really familiar with workers. 我对工人并不熟悉。 Am I right in thinking this it is loading the worker.js code in a completely separate environment (basically a background thread) so it doesn't have access to window. 我是否认为这是在一个完全独立的环境(基本上是后台线程)中加载worker.js代码,因此它无法访问窗口。

在worker的.js文件中:

importScripts('../relative/path/lib.min.js', '../../other/lib.js');

In order to prevent web workers from running into concurrency problems, the web worker spec prevents the worker from having access to the window object or the DOM. 为了防止Web worker遇到并发问题,Web worker规范阻止了worker访问window对象或DOM。

The only objects and methods available inside a worker are: 工作者中唯一可用的对象和方法是:

  1. The navigator object 导航器对象
  2. The location object 位置对象
  3. XMLHttpRequest XMLHttpRequest的
  4. The setTimeout and clearTimeout functions. setTimeout和clearTimeout函数。
  5. The Application Cache 应用程序缓存
  6. Spawning other Web Workers 产卵其他网络工作者
  7. Using a webworker specific method to load other scripts 使用webworker特定方法加载其他脚本

So whilst you could use the worker to create the XMLHttpRequest manually; 因此,您可以使用worker手动创建XMLHttpRequest; Jquery or any other library which expects to be able to access the DOM or Window Object is never going to work in there. 期望能够访问DOM或Window对象的Jquery或任何其他库永远不会在那里工作。

Yeah it has been correctly pointed out to me that the ajax call is asynchronous so the worker is not required. 是的,我已正确地指出ajax调用是异步的,因此不需要worker。 For circumstances which I won't explain turns out that the ajax call didn't work anyway, so I reverted back to the XMLHttpRequest how it was and left it using a worker. 对于我不会解释的情况,结果是ajax调用无论如何都没有用,所以我回到了XMLHttpRequest它是怎么回事并让它使用了一个worker。

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

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