HTML Web Worker和Jquery Ajax调用

Tri*_*Tri 40 ajax jquery html5 web-worker

我想知道我是否可以在web worker文件中使用jQuery.谷歌浏览器给了我这个错误:"未捕获的ReferenceError:$未定义".

这是代码:父文件:

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);
}
Run Code Online (Sandbox Code Playgroud)

工人档案:

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) {

    }
  });
}
Run Code Online (Sandbox Code Playgroud)

请帮忙,谢谢:)

Cas*_*jne 38

不,你不能.无法访问非线程安全组件或DOM,您必须通过序列化对象将特定数据传入和传出线程.因此,您必须非常努力地在代码中导致问题.jQuery是一个JavaScript DOM库.

但是,您可以XMLHttpRequest在工作中使用本机.

并且,导入外部脚本不会通过带有script标记的页面进行:在工作文件中使用importScripts().


She*_*zod 24

这是我发现的:

您可以使用该importScripts()函数将外部脚本文件或库加载到worker中 .

http://www.html5rocks.com/en/tutorials/workers/basics/#toc-enviornment-loadingscripts

importScripts('script1.js');
importScripts('script2.js');
Run Code Online (Sandbox Code Playgroud)

要么

importScripts('script1.js', 'script2.js');
Run Code Online (Sandbox Code Playgroud)

虽然,你无法加载jQuery,因为jQuery需要DOM访问权限,而Web工作者则没有.