My project structure looks like
js
/client.js
/script1.js
/webWoker.js
node_modules
.gitignore
index.html
The main.html
has it included as well in
<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>
My script1.js
looks like
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);
};
}
and my webWorker.js
looks like
onmessage = function (e) {
console.log('Message received from main script');
var result = "#27ae60";
console.log('Posting message back to main script');
postMessage(result);
};
I use node.js
for this project and run it via npm start
, and when I run this in browser I see
script1.js:81 GET http://localhost:8080/webWorker.js 404 (Not Found)
execute @ script1.js:81
img.onload @ script1.js:64
What is going wrong here?
You don't have to include the worker script in your main page (it's even a bad idea), but the URI you pass to new Worker(URI)
is relative to the current documentURI.
So in your case, it should be new Worker("/js/webWorker.js");
.