Uncaught ReferenceError: importScripts is not defined

自作多情 提交于 2019-11-28 22:41:41

This code needs to be inside a worker script. The worker itself is created via a new Worker object - see Getting Started in the tutorial.

The code you've linked is inside the worker created here.

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.

// 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.

Happy coding!

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.

I avoided this error by wrappig the worker.js file with:

    if( 'undefined' === typeof window){
       importScripts('workerscript2.js');
    ...
    }

Please refer to the comment below by Rob, which offers an alternative solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!