Html importScripts(网络工作者)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16310091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
importScripts (web workers)
提问by Vincent
I have tried to use importScripts to load a second JavaScript file into my web worker, but although no error occurred, it didn't work. I narrowed the problem down to this very simple situation:
我曾尝试使用 importScripts 将第二个 JavaScript 文件加载到我的 Web Worker 中,但尽管没有发生错误,但它不起作用。我将问题缩小到这个非常简单的情况:
In the main HTML file:
在主 HTML 文件中:
<script>
var w = new Worker("script1.js");
w.addEventListener("message", function(e){
alert(e.data);
})
w.postMessage();
</script>
In script1.js:
在 script1.js 中:
self.addEventListener("message", function(e){
var a = 5;
importScripts("script2.js");
self.postMessage(a);
})
In script2.js:
在 script2.js 中:
a = 6
I would like to see a dialog displaying 6, because a was changed from 5 to 6 by importing script2.js, but the dialog shows 5. What am I missing here?
我想看到一个显示 6 的对话框,因为通过导入 script2.js 将 a 从 5 更改为 6,但对话框显示 5。我在这里遗漏了什么?
回答by dandavis
Using var a
in the function means that a
will always be private. Since importScripts adds to the global scope, JS prefers to access the more localized a
in the function that posts a
. You can post self.a
instead, which shall be 6, as you expected.
var a
在函数中使用意味着a
永远是私有的。由于importScripts 添加到全局范围,JS 更喜欢访问a
post 函数中更本地化的内容a
。您可以self.a
改为发布,如您所料,应该是 6。
EDIT: Someone recently asked me about this in person, so I made a demo to clarify the behaviour: http://pagedemos.com/importscript/
编辑:最近有人亲自问过我这个问题,所以我做了一个演示来澄清行为:http: //pagedemos.com/importscript/