Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: importScripts is not defined

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/

I'm using chrome.

I'm using https://code.google.com/p/bitjs/ and it begins with

importScripts('io.js');
importScripts('archive.js');
like image 907
netdigger Avatar asked Jan 24 '13 11:01

netdigger


People also ask

What is importScripts?

# Disallowing asynchronous importScripts() importScripts() tells your main service worker script to pause its current execution, download additional code from a given URL, and run it to completion in the current global scope. Once that's done, the main service worker script resumes execution.

How do I import a script into service worker?

ES modules can be imported in one of two ways: either statically, using the import ... from '...' syntax, or dynamically, using the import() method. Inside of a service worker, only the static syntax is currently supported. This limitation is analogous to a similar restriction placed on importScripts() usage.


3 Answers

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!

like image 78
SJ Anderson Avatar answered Oct 31 '22 12:10

SJ Anderson


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.

like image 44
Bergi Avatar answered Oct 31 '22 13:10

Bergi


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.

like image 16
gm2008 Avatar answered Oct 31 '22 13:10

gm2008