HTML5 Web Worker

  sonic0002        2012-12-02 06:25:00       9,546        0    

Web Worker is a JavaScript multithreading solution provided by HTML5. we can put some compute intensive codes into Web Worker and it will not hang the user interface.

1. How to use Web Worker

Web Worker's basic mechanism is to use Worker to load a JavaScript file to create a new thread in JavaScript's main thread. It will not block other thread's execution and will provide a data exchange interface between main thread and new thread : postMessage() and onmessage.

Let's look at an example:

//worker.js
onmessage =function (evt){
var d = evt.data;//Get sent data with evt.data
postMessage( d );//Send message to the main thread
}

HTML Page : test.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
//WEB Main Thread
var worker =new Worker("worker.js"); //Create a Worker thread and put an URL to load the script
worker.postMessage("hello world"); //Send data to worker
worker.onmessage =function(evt){ //Receive data from worker
console.log(evt.data); //Output data sent by worker
}
script>
head>
<body>body>
html>

Open test.html page with Chrome, the console will output "hello world" if it executes successfully.

We can find Web Worker's execution can be viewed as :

WEB main thread:

1. Through worker=new Worker(url) to load a JS file to create a new worker and return a worker instance;

2. Send data to worker with worker.postMessage(data)

3. Bind worker.onmessage to receive data from worker

4. We can use worker.terminate() to terminate the execution of a worker.

worker new thread:

1. Send data to main thread with postMessage(data)

2. Bind onmessage to receive data from main thread.

2. What can Worker do

After knowing how to use Web Worker, then what problems can it solve for us? We can take fibonacci array as an example.

In math, fibonacci array is defined as recursive: F0=0,F1=1,Fn=F(n-1)+F(n-2) (n>=2,n∈N*). Use normal JavaScript, it's :

var fibonacci =function(n) {
return n <2? n : arguments.callee(n -1) + arguments.callee(n -2);
};
//fibonacci(36)

When n is 39, the execution time is 19097 ms in Chrome, if n is 40, the browser will prompt that the script is long running.

Because JavaScript is single threaded, when calculate the fibonacci, it cannot execute other scripts, UI rendering thread will also hang. With Web Worker, we can put the calculation into a new thread to avoid the hang of UI.

//fibonacci.js
var fibonacci =function(n) {
return n <2? n : arguments.callee(n -1) + arguments.callee(n -2);
};
onmessage
=function(event) {
var n = parseInt(event.data, 10);
postMessage(fibonacci(n));
};

HTML Page, fibonacci.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>web worker fibonaccititle>
<script type="text/javascript">
onload
=function(){
var worker =new Worker('fibonacci.js');
worker.addEventListener(
'message', function(event) {
var timer2 = (new Date()).valueOf();
console.log(
'结果:'+event.data, '时间:'+ timer2, '用时:'+ ( timer2 - timer ) );
},
false);
var timer = (new Date()).valueOf();
console.log(
'开始计算:40','时间:'+ timer );
setTimeout(
function(){
console.log(
'定时器函数在计算数列时执行了', '时间:'+ (new Date()).valueOf() );
},
1000);
worker.postMessage(40
);
console.log(
'我在计算数列的时候执行了', '时间:'+ (new Date()).valueOf() );
}
script>
head>
<body>
body>
html>

Open fibonacci.html in Chrome, the output will be:

开始计算:40 时间:1316508212705
我在计算数列的时候执行了 时间:
1316508212734
定时器函数在计算数列时执行了 时间:
1316508213735
结果:
102334155 时间:1316508262820 用时:50115

This example explains that when the worker executes the fibonacci array calculation, it will not affect the execution of main thread, it will execute in its own thread and return the result to the main thread after completion of calculation.

3. Other uses of Worker

We now know that Worker will create a new thread by accepting a URL, then can we use web worker to do some jsonp like requests? We know that jsonp is to load json data by adding script tags, while script elements are blocking when loading and executing. We can use web worker here.

The following example will load some 169.42 KB JSON data.

// /aj/webWorker/core.js
function $E(id) {
return document.getElementById(id);
}
onload
=function() {
//通过web worker加载
$E('workerLoad').onclick =function() {
var url ='http://js.wcdn.cn/aj/mblog/face2';
var d = (new Date()).valueOf();
var worker =new Worker(url);
worker.onmessage
=function(obj) {
console.log(
'web worker: '+ ((new Date()).valueOf() - d));
};
};
//通过jsonp加载
$E('jsonpLoad').onclick =function() {
var url ='http://js.wcdn.cn/aj/mblog/face1';
var d = (new Date()).valueOf();
STK.core.io.scriptLoader({
method:
'post',
url : url,
onComplete :
function() {
console.log(
'jsonp: '+ ((new Date()).valueOf() - d));
}
});
};
//通过ajax加载
$E('ajaxLoad').onclick =function() {
var url ='http://js.wcdn.cn/aj/mblog/face';
var d = (new Date()).valueOf();
STK.core.io.ajax({
url : url,
onComplete :
function(json) {
console.log(
'ajax: '+ ((new Date()).valueOf() - d));
}
});
};
};

HTML page: /aj/webWorker/worker.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Worker example: load datatitle>
<script src="http://js.t.sinajs.cn/STK/js/gaea.1.14.js" type="text/javascript">script>
<script type="text/javascript" src="http://js.wcdn.cn/aj/webWorker/core.js">script>
head>
<body>
<input type="button" id="workerLoad" value="web worker加载">input>
<input type="button" id="jsonpLoad" value="jsonp加载">input>
<input type="button" id="ajaxLoad" value="ajax加载">input>
body>
html>

Set HOST:

127.0.0.1 js.wcdn.cn

By loading http://js.wcdn.cn/aj/webWorker/worker.html The output is:

web worker: 174
jsonp:
25
ajax:
38

4. Conclusion

Pros:

1. Web Worker can load a JS file for large computation without hanging the main thread, and communicate with postMessage and onmessage.

2. Can use ImportScripts(url) to load other script files

3. Can use setTimeout(), clearTimeout(), setInterval() and clearInterval()

4. We can use XMLHttpRequest() to send request

5. Can access some properties of navigator

Cons:

1. Cannot load JS cross site

2. Codes in Worker cannot access DOM

3. Different browsers have different support for Worker.

4. Not every browser supports this.

Source : http://www.cnblogs.com/feng_013/archive/2011/09/20/2175007.html

JAVASCRIPT  HTML  WEB WORKER 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

Be careful with mathematician

A mathematician was interviewing for a job. The interviewer asks him - "You are walking towards your office and running late for a very important meeting and you glimpse a building on fire with people screaming for help. What will you do?".The mathematician thinks for a while and replies : "People's