如何在 Web Worker 中使用其他库?
我有一些像这样的 javascript 代码,
var worker = new Worker("javascript/worker.js");
worker.onmessage = function(evt)
{
// stuff
}
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();
}
});
}
worker.js 文件没有包含 jQuery,所以不起作用。如果我将其添加到worker.js,
importScripts("jQuery.js");
那么我会收到消息,
Uncaught ReferenceError: window is not defined
我不太熟悉workers。我的想法是否正确,它正在完全独立的环境(基本上是后台线程)中加载worker.js代码,因此它无法访问window.js。
I have some javascript code like this,
var worker = new Worker("javascript/worker.js");
worker.onmessage = function(evt)
{
// stuff
}
worker.js looks like this,
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. If I add this to 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在工作人员的 .js 文件上:
On the worker's .js file:
为了防止 Web Worker 遇到并发问题,Web Worker 规范阻止 Worker 访问窗口对象或 DOM。
工作线程中唯一可用的对象和方法有:
因此,虽然您可以使用 Worker 手动创建 XMLHttpRequest; Jquery 或任何其他期望能够访问 DOM 或 Window 对象的库永远不会在那里工作。
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.
The only objects and methods available inside a worker are:
So whilst you could use the worker to create the XMLHttpRequest manually; Jquery or any other library which expects to be able to access the DOM or Window Object is never going to work in there.
是的,已经正确地向我指出 ajax 调用是异步的,因此不需要工作人员。对于我不会解释的情况,事实证明 ajax 调用无论如何都不起作用,所以我恢复到 XMLHttpRequest 的原样并使用工作人员保留它。
Yeah it has been correctly pointed out to me that the ajax call is asynchronous so the worker is not required. 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.