HTML5 web worker, just like creating a new thread in java, creates an independent environment to run a program with a relatively large amount of computing. Currently, it is not very useful, however, it is estimated that it may be used in the future.
The basic code is simple:
[Html]
Var worker = new Worker ('dowork. js ');
Worker. addEventListener ('message', function (e ){
Console. log ('worker said: ', e. data );
}, False );
Worker. postMessage ('Hello World'); // Send data to our worker.
DoWork. js
[Html]
Self. addEventListener ('message', function (e ){
Self. postMessage (e. data );
}, False );
Note that we need to establish a two-way communication mechanism on the page: postMessage and addEventListener (in page we need postMessage () to post it to worker and onmessage to receive from worker)
Two-way communication mechanism (in worker we also need postMessage to post it to page and on message to receive from page) should also be established in worker. js)
Others should note that error handling and FileURL can be used if you do not want to create a separate worker. js (use objectURL to load worker in the same page)
[Html]
// Prefixed in Webkit, Chrome 12, and FF6: window. WebKitBlobBuilder, window. Empty blobbuilder
Var bb = new BlobBuilder ();
Bb. append ("onmessage = function (e) {postMessage ('msg from worker ');}");
// Obtain a blob URL reference to our worker 'file '.
// Note: window. webkitURL. createObjectURL () in Chrome 10 +.
Var blobURL = window. URL. createObjectURL (bb. getBlob ());
Author: baoeni