Comments: When testing the worker api, many people always encounter exceptions and cannot test the effect at all. Note that a simple text file cannot implement worker, the actual code you write must be deployed on the server (tomcat. jBoss, etc.) to run the worker api many people always encounter exceptions when testing the worker api, and the test results are not effective at all.
When using worker, you must note that a simple text file cannot implement worker. The actual code you write must be deployed on the server (tomcat. jBoss, etc.) to run the worker api.
Below is a simple example.
Js Code test. js (worker)
The Code is as follows:
Function messageHandler (e ){
PostMessage ("worker says:" + e. data + "too ");
}
AddEventListener ("message", messageHandler, true );
PostMessage ("2222222222 ");
Html code index.html
The Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Title> index.html </title>
<Meta http-equiv = "keywords" content = "keyword1, keyword2, keyword3">
<Meta http-equiv = "description" content = "this is my page">
<Meta http-equiv = "content-type" content = "text/html; charset = UTF-8">
<! -- <Link rel = "stylesheet" type = "text/css" href = "./styles.css"> -->
</Head>
<Body>
<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 ");
</Script>
</Body>
</Html>
The index.html page is directly merged, and then the string sent by the worker is displayed on the console Panel of the browser (json transfer is generally used in actual applications ).