Search code examples
javascriptimportweb-worker

Can a script imported by a Web-Worker in turn import another script?


The pattern for a script used by a webworker https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers is:

  • webworker.js

    importScripts('./parent.js')
    
  • parent.js

    import { PerfManager} from "./child.js";
    

The child.js import results in:

Uncaught SyntaxError: Cannot use import statement outside a module

Is there any way to implement an import within the parent.js when used by webworker.js ?


Solution

  • You can start a module Worker (currently only available in Blink based browsers).

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

    Then instead of importScripts you will directly import parent.js from this worker script, which will in turn be able to import whatever dependency.

    Since StackSnippets are in null-origined iframes, I have to outsource the demo to this plnkr.


    Note that in these browsers you could even use the dynamic import() statement from parent.js even in a non module Worker: plnkr, but this still wouldn't work in browsers that don't support module Workers.
    For these you need to use only non module scripts and to use importScripts and its globals all along the chain: plnkr.