HTML5 與Web Workers通信
Web Workers生成以后,就可以使用postMessage API傳送和接收數(shù)據(jù)了。postMessage還支持跨框架和跨窗口通信。下面將通過一個(gè)實(shí)例來汫解如何與Web Workers通信。
△【例題】與Web Workers通信
代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>計(jì)數(shù)結(jié)果:<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>
點(diǎn)擊加載更多評(píng)論>>