1. Overview
HTML5 Web Worker allows Javascript programs to execute a large number of time-consuming computing tasks in a single thread in the background. Web Worker cannot directly access the DOM during execution. Web Worker also consumes CPU and system resources. The communication between the Web Worker and the page can be performed through the postMessage and message events in the Web Worker method.
2. browser support Detection
Function loadDemo ()
{
If (typeof (Worker )! = "Undefined ")
{
Document. getElementById ("support"). innerHTML =
"Excellent! Your browser supports HTML5 Web Workers ";
}
}
3. worker object
A worker object is a child object of a window object. It has the following methods:
• Worker (jsFile_URL): constructor. The parameter is the URL of a JavaScript file used to execute a Web Worker task. It can be a relative or absolute address. You can build a worker recursively. Call on the page.
• Terminate (): terminate a worker. It cannot be reused after termination and can only be rebuilt.
Call on the page.
• Close (): Terminate the worker and call it within the Worker.
• ImportScripts (jsFile_1_URL, jsFile_2_URL,...): Imports JavaScript files to an existing worker asynchronously, and JavaScript is executed in the order of parameters. It is called within the Worker script.
• PostMessage (msg): The method for creating a werker page to communicate with worker, for example:
// ------------- Send a message from the page to the worker ------------------
Document. getElementById ("helloButton"). onclick = function (){
Worker. postMessage ("Here's a message for you ");
}
// ------------- The page receives messages from worker ----------------
Worker. addEventListener ("message", messageHandler, true );
Function messageHandler (e ){
// Process message from worker
}
// ------------- JavaScript file processing message from page ----------------
AddEventListener ("message", messageHandler, true );
Function messageHandler (e ){
PostMessage ("worker says:" + e. data + "too ");
}
4. handle errors
// ------------- Process the message from worker on the page ----------------
Worker. addEventListener ("error", errorHandler, true );
Function errorHandler (e ){
Console. log (e. message, e );
}
5. Use a timer
Although the worker cannot directly access the objects in the DOM, it can completely use the time-related methods and attributes in the window object, or use some other attributes. For example:
Var t = setTimeout (postmessages, 2000, "delayed message ");