位置:首頁(yè) > 軟件操作教程 > 編程開(kāi)發(fā) > HTML > 問(wèn)題詳情

HTML5 與Web Workers通信

提問(wèn)人:劉團(tuán)圓發(fā)布時(shí)間:2020-11-17

Web Workers生成以后,就可以使用postMessage API傳送和接收數(shù)據(jù)了。postMessage還支持跨框架和跨窗口通信。下面將通過(guò)一個(gè)實(shí)例來(lái)汫解如何與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()">開(kāi)始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> 

image.png

繼續(xù)查找其他問(wèn)題的答案?

相關(guān)視頻回答
回復(fù)(0)
返回頂部