Many people always encounter exceptions when testing the worker API and cannot test the effect at all.
One thing you must pay attention to when using workers is that a simple text file cannot implement a worker. The actual code you write must be deployed to the server (tomcat.jBoss, etc.) to run the worker api.
Write a simple example below
js code test.js (worker)
function messageHandler(e) {
postMessage("worker says: " e.data " too");
}
addEventListener("message", messageHandler, true);
postMessage("2222222222");
html code index.html
< head>
index.html
-->
< ;script type="text/javascript">
if(typeof(Worker)!=="undefined"){
console.log("zhichi worke");
}else{
console.log("no support!");
}
function messageHandler(e){
console.log(e.data);
}
function errorHandler(e){
console.log(e.message, e);
}
var myWorker = new Worker("task.js");
myWorker.addEventListener("message", messageHandler, true);
myWorker.addEventListener("error", errorHandler, true);
myWorker.postMessage("1 fangsong d");
< /html>
Instead of directly accessing the index.html page afterwards, you will see the string sent by the worker in the console panel of the browser (json transmission is generally used in actual applications).