browser-image-compression icon indicating copy to clipboard operation
browser-image-compression copied to clipboard

[WebWorker] nextZero ReferenceError: module is not defined

Open binlux opened this issue 5 years ago • 1 comments

when using web worker i got this error. web worker failed to load the script when compressing for the first time.

(i'm using MeteorJS + ReactJS) Capture

binlux avatar Jan 09 '21 22:01 binlux

from stackoverflow: https://stackoverflow.com/questions/14500091/uncaught-referenceerror-importscripts-is-not-defined

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.

binlux avatar Jan 10 '21 15:01 binlux