Search code examples
es6-modulesweb-worker

Reliable way to detect if running in module vs classic web-worker?


I'm working on some code that needs to change its behavior (using import() vs importScripts()) when running in a module worker. Is there any kind of way to detect what "type" of WebWorker you're running in?

The only way I can think of is using this in chrome, but obviously this isn't a great solution...

let isModuleWorker = false;
try {
 importScripts('about:blank')
} catch(e) {
  // the full error text in *chrome* is "Module scripts don't support importScripts()"
  isModuleWorker = e.message.contains('Module scripts');
}

This is clearly not a good solution, but I haven't seen anything else I can use to make this distinction. Does anyone have a better idea?


Solution

  • Thanks to Jason Miller on twitter for the answer here:

    function isModule() {
      try{ 
       importScripts("data:,"); 
       return false; 
      } catch(e) {}
      return true;
    }
    

    Should work. As opposed to about:blank, this one won't throw in a classic worker. :)