HTML5 與Web Workers通信
Web Workers生成以后,就可以使用postMessage API傳送和接收數據了。postMessage還支持跨框架和跨窗口通信。下面將通過一個實例來汫解如何與Web Workers通信。
△【例題】與Web Workers通信
代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>計數結果:<output id="result"></output></p>
<button onclick="start()">開始worker</button>
<button onclick="stop()">停止worker</button>
<script type="text/javascript">
var w;
function start(){
if(typeof(Worker)!="undefined"){
if(typeof(w)=="undefined"){
w = new Worker("webworker.js");
}
w.onmessage = function(e){
document.getElementById("result").innerHTML=e.data;
};
}else{
document.getElementById("result").innerHTML="sorry,your browser does not support web workers";
}
}
function stop(){
w.terminate();
w=undefined;
}
</script>
</body>
</html>

點擊加載更多評論>>