Web工作者没有单独的Javascript文件? [英] Web workers without a separate Javascript file?

查看:83
本文介绍了Web工作者没有单独的Javascript文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,网络工作者需要在一个单独的JavaScript文件中编写,并且这样调用:

As far as I can tell, web workers need to be written in a separate JavaScript file, and called like this:

new Worker('longrunning.js')

我正在使用闭包编译器来组合和缩小我所有的JavaScript源代码,我宁愿不必将我的工作人员放在单独的文件中进行分发。有没有办法做到这一点?

I'm using the closure compiler to combine and minify all my JavaScript source code, and I'd rather not have to have my workers in separate files for distribution. Is there some way to do this?

new Worker(function() {
    //Long-running work here
});

鉴于一流函数对JavaScript至关重要,为什么做后台工作的标准方法必须从服务器加载整个'nother JavaScript文件?

Given that first-class functions are so crucial to JavaScript, why does the standard way to do background work have to load a whole 'nother JavaScript file from the server?

推荐答案

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


如果要动态创建工作脚本,或创建自包含页面而不必创建单独的工作文件,该怎么办?使用Blob(),您可以通过以字符串形式创建工作人员代码的URL句柄,将您的工作人员内联在与主逻辑相同的HTML文件中

What if you want to create your worker script on the fly, or create a self-contained page without having to create separate worker files? With Blob(), you can "inline" your worker in the same HTML file as your main logic by creating a URL handle to the worker code as a string


<!DOCTYPE html>
<script id="worker1" type="javascript/worker">
  // This script won't be parsed by JS engines because its type is javascript/worker.
  self.onmessage = function(e) {
    self.postMessage('msg from worker');
  };
  // Rest of your worker code goes here.
</script>
<script>
  var blob = new Blob([
    document.querySelector('#worker1').textContent
  ], { type: "text/javascript" })

  // Note: window.webkitURL.createObjectURL() in Chrome 10+.
  var worker = new Worker(window.URL.createObjectURL(blob));
  worker.onmessage = function(e) {
    console.log("Received: " + e.data);
  }
  worker.postMessage("hello"); // Start the worker.
</script>

这篇关于Web工作者没有单独的Javascript文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆