0

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?

Royi Hagigi
  • 240
  • 1
  • 10
  • Sounds like an XY problem. By the time you run this check your module code would probably have triggered a SyntaxError anyway. Why can't you feature detect at the Worker construction? See https://stackoverflow.com/questions/62954570/javascript-feature-detect-module-support-for-web-workers – Kaiido Mar 21 '23 at 22:56
  • Because this is running inside of a library that gets used on both classic and module workers and needs to avoid calling importScripts in the module worker. – Royi Hagigi Mar 23 '23 at 20:18
  • Then provide two builds of your library, one a .esm one and a .classic one. Trying to mix these won't work. – Kaiido Mar 23 '23 at 23:07

1 Answers1

1

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. :)

Royi Hagigi
  • 240
  • 1
  • 10
  • You actually want it to be `"data:text/javascript,"` see https://github.com/whatwg/html/issues/8869 – Kaiido Mar 21 '23 at 22:54