【发布时间】:2011-06-17 20:31:51
【问题描述】:
我想知道是否可以在 web worker 文件中使用 jQuery。谷歌浏览器给了我这个错误:“Uncaught ReferenceError: $ is not defined”。
代码如下: 父文件:
var loader = new Worker(BASE_URL + "js/rss_loader_worker.js");
// Ask the worker to start loading the RSS from the server
loader.postMessage("loadRss");
// When receive the response from the server
loader.onmessage = function (event) {
console.log(event.data);
}
工人档案:
onmessage = function (event) {
if (event.data === "loadRss") {
loadRss();
}
}
/**
* This function handles the AJAX request to the server side
* then pass the content to the view page
* @param none
* @return html text
*/
loadRss = function () {
$.ajax({
data: {city: CITY_LOCATION},
url: BASE_URL + "/getfeeds",
onsucess: function (data) {
}
});
}
请帮忙,谢谢:)
【问题讨论】:
-
importScripts("jquery.js");不能工作:jQuery 使用'window' 变量,网络工作者无法访问该变量。但是您可以使用其他库来完成这项工作 =)
-
为了让入站搜索者清楚,从
Worker运行 ajax 请求是可能的,而且通常是有益的。与传统的jQuery不同,因为jQuery是一个DOM 操作库,而Web Worker 有一个WorkerGlobalScope而不是Window,因此无法访问文档或DOM。
标签: jquery ajax html web-worker