Web Workers - How To Import Modules Web Workers - How To Import Modules javascript javascript

Web Workers - How To Import Modules


ES2015 modules in Workers are available in Desktop Safari and in Chromium browsers.

If other browsers / versions are your target, you still need to use importScripts().

When available, you create a module-worker like this:

new Worker("worker.js", { type: "module" });

See: https://html.spec.whatwg.org/#module-worker-example

These are the bug-reports for each browser:

  • Firefox: In development 🛑 please vote!
  • Chromium Browsers:
    Dedicated Workers: Available since version 80 ✔️
    Shared Workers: Available since version 83 ✔️
    Service Workers: Available since version 91 ✔️
  • Webkit:
    Safari Desktop: Available since Safari 14.1 ✔️
    Safari Mobile (iOS): Available since Safari 15 ✔️


2020:

Chrome 80 has shipped module workers in February 2020 (and Chrome 82 will ship modules for shared workers). Firefox/Safari do not support those features for now: tests

You may use want to use import-from-worker lib to do the heavy lifting for you (for now, you need to check the support for modules in workers and do the fallback yourself).


ES Modules in workers are already available in Chrome, enabling Experimental Web Platform Features, using the proper flag when launching chrome:

chrome.exe --enable-experimental-web-platform-features

This is the syntax you need to use to load the worker script as a module :

new Worker( 'my-worker.js', { type : 'module' } );

This feature has been in development for almost ayear, and should be available soon, without the need of special flags, however, there is no official release date yet.