我正在从事一个严重依赖网络工作者的项目.但我无法让它们按要求运行.这只是一个缩小的示例,但格式或多或少相似.
我有4个文件:
指数html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World!</title>
</head>
<body>
<button id="btn">GO</button>
<script src="./指数js公司" type="module"></script>
</body>
</html>
指数js公司
const worker = new Worker("./工人js公司", {type: "module"})
worker.addEventListener("message", async ({ data }) => {
console.log(data);
});
worker.onerror = function (event) {
throw new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
}
window.sendMessage = function (args) {
worker.postMessage(args);
};
async function onclick() {
sendMessage("World")
}
document.getElementById("btn").addEventListener("click", onclick, false);
工人js公司
import * as p from "你好js公司"
console.log("Worker Started")
onmessage = function (e) {
p.greet(e.data)
}
你好js公司
export function greet(who){
alert("Hello " + who)
}
工人应输出"工人已启动".
单击按钮时,UI线程将向worker发送一条消息,worker随后将调用greet
函数.
但是,worker立即出错并通过worker.onerror
返回值
它返回的 chromium (和 chromium 基)值未定义
Uncaught Error: undefined (undefined:undefined)
at Worker.worker.onerror (指数js公司:8:11)
我已经在两台有3种不同操作系统的计算机上测试了不同浏览器,但没有成功.
据我所知.Firefox不支持我这样做.
Uncaught Error: SyntaxError: import declarations may only appear at top level of a module (http://localhost:8000/工人js公司:1)
我在这里看了一下这个答案
使用运行chrome
示例通过以下方式与本地服务器一起运行
python -m http.server
这是一个包含文件的存储库