gpt4 book ai didi

javascript - 是否可以在 WebWorker 中加载 JavaScript 文件?

转载 作者:行者123 更新时间:2023-11-30 14:53:31 25 4
gpt4 key购买 nike

我有一个 WebWorker,我从它开始

new Worker("worker.js");

在这个 worker 中,我尝试通过以下方式加载所需的 JavaScript 文件,但没有成功

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

如何解决这个问题并在我的 WebWorker 中包含所需的 JavaScript 文件?

编辑:

我收到错误消息:

Uncaught ReferenceError: NeededJs is not defined

谢谢

这是我需要包含的文件 File I need to Inlcude

最佳答案

是的,这是可能的。你应该注意到它是一个全局函数,所以删除 self.

来自: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:

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.

此外,当您为导入的文件使用模块模式时,您需要传递一个选项来指定:

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

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

关于javascript - 是否可以在 WebWorker 中加载 JavaScript 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47757209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com