web worker在执行时抛出404

时间:2017-04-19 01:39:04

标签: javascript node.js web-worker

我的项目结构看起来像

js
  /client.js
  /script1.js
  /webWoker.js
node_modules
.gitignore
index.html

main.html也包含在

<script type="text/javascript" src="js/script1.js"></script>
<script type="text/javascript" src="js/client.js"></script>
<script type="text/javascript" src="js/webWoker.js"></script>

我的script1.js看起来像

if (window.Worker) {
    console.log("uri: " + document.documentURI);
    var myWorker = new Worker("myworker.js");
    myWorker.postMessage("hello");
    console.log(myWorker);

    myWorker.onmessage = function (e) {
        result.textContent = e.data;
        console.log('Message received from worker: ' + result.textContent);
    };
}

我的webWorker.js看起来像

onmessage = function (e) {
    console.log('Message received from main script');
    var result = "#27ae60";
    console.log('Posting message back to main script');
    postMessage(result);
};

我将node.js用于此项目并通过npm start运行,当我在浏览器中运行时,我看到了

script1.js:81 GET http://localhost:8080/webWorker.js 404 (Not Found)
execute @ script1.js:81
img.onload @ script1.js:64

这里出了什么问题?

1 个答案:

答案 0 :(得分:3)

您不必在主页中包含工作脚本(这甚至是个坏主意),但传递给new Worker(URI)的URI是相对于当前的documentURI。 / p>

所以在你的情况下,它应该是new Worker("/js/webWorker.js");