Javascript 未捕获的 ReferenceError:未定义 importScripts
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14500091/
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
Uncaught ReferenceError: importScripts is not defined
提问by netigger
Why do I keep getting this error?
为什么我一直收到这个错误?
I should be able to use this global function right?
我应该可以使用这个全局函数吧?
http://www.html5rocks.com/en/tutorials/workers/basics/
http://www.html5rocks.com/en/tutorials/workers/basics/
I'm using chrome.
我正在使用铬。
I'm using https://code.google.com/p/bitjs/and it begins with
我正在使用https://code.google.com/p/bitjs/并以
importScripts('io.js');
importScripts('archive.js');
采纳答案by Bergi
This code needs to be inside a worker script. The worker itself is created via a new Workerobject - see Getting Startedin the tutorial.
此代码需要在工作脚本中。工作器本身是通过一个新Worker对象创建的- 请参阅教程中的入门。
The code you've linked is inside the worker created here.
您链接的代码位于此处创建的工作线程中。
回答by SJ Anderson
When you create a worker it is actually executed twice. The first pass is in the context of the global 'window' object(meaning you have access to all the window object functions). The second call through is in the context of the worker which has a different global object, one where 'importScripts' exists.
当您创建一个工作程序时,它实际上会执行两次。第一遍是在全局“窗口”对象的上下文中(意味着您可以访问所有窗口对象函数)。第二个调用是在具有不同全局对象的 worker 的上下文中,其中存在 'importScripts'。
// proper initialization
if( 'function' === typeof importScripts) {
importScripts('script2.js');
addEventListener('message', onMessage);
function onMessage(e) {
// do some work here
}
}
Notice the addEventListener is inside the if statement. If you place it outside of it, your callback will be registered twice. Once on the 'window' global and once on the worker's global.
注意 addEventListener 在 if 语句中。如果你把它放在外面,你的回调将被注册两次。一次在“窗口”全局上,一次在工作人员的全局上。
Happy coding!
快乐编码!
回答by gm2008
I encountered this error as well. In my case, it is because I am testing the code using Karma/Jasmine. Due to the test framework, the worker.js file is loaded by main thread as well.
我也遇到了这个错误。就我而言,这是因为我正在使用 Karma/Jasmine 测试代码。由于测试框架的原因,worker.js 文件也由主线程加载。
I avoided this error by wrappig the worker.js file with:
我通过包装 worker.js 文件避免了这个错误:
if( 'undefined' === typeof window){
importScripts('workerscript2.js');
...
}
Please refer to the comment below by Rob, which offers an alternative solution.
请参阅下面 Rob 的评论,它提供了另一种解决方案。

