简体   繁体   中英

Is it possible to load JavaScript file in a WebWorker?

I have a WebWorker which I start with

new Worker("worker.js");

in this worker I try to load a needed JavaScript file without success via

self.importScripts("NeededJs.js");
const m = new NeededJs();

How can I solve this issue and include the needed JavaScript File in my WebWorker ?

Edit:

I get the error msg :

Uncaught ReferenceError: NeededJs is not defined

Thanks

This is the File I need to include File I need to Inlcude

Yes, it is possible. You should note its a global function so remove the self.

from: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers

Worker threads have access to a global function, importScripts(), which lets them import scripts. It accepts zero or more URIs as parameters to resources to import; all of the following examples are valid:

and

Note: Scripts may be downloaded in any order, but will be executed in the order in which you pass the filenames into importScripts() . This is done synchronously; importScripts() does not return until all the scripts have been loaded and executed.

Also, as you are using the module pattern for your imported file you need to pass an option to specify that:

from: https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM