当在 HTML 页面中执行脚本时,页面的状态是不可响应的,直到脚本已完成。

Web Workers 是运行在后台的 JavaScript线程,独立于其他脚本,不会影响到前端其他任何操作或体验。

主要过程包括:
1、创建Worker对象;
2、将参数值传递通过Worker对象的postMessage方法传递传递给后台线程脚本;
3、后台线程脚本处理后将结果通过postMessage方法返回;
4、原脚本通过监听onMessage事件获取后台线程传过来的值。

实例代码如下:

html页面:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 5         <title>无标题文档</title>
 6         <script type="text/javascript" src="bb.js">
 7         </script>
 8     </head>
 9     <body>
10         输入数值:<input type="text" id="num"><input type="button" id="button" value="计算" />
11     </body>
12 </html>

bb.js代码:

 1 window.onload = function() {
 2     var worker = new Worker("sumCalculate.js");
 3     console.log(worker);
 4     var bbDom = document.getElementById("button");
 5     
 6     bbDom.addEventListener("click", f);
 7     
 8     function f(){
 9         var num = parseInt(document.getElementById("num").value);
10         worker.postMessage(num);
11     }
12 
13     worker.onmessage = function(event) {
14         alert(event.data);
15     }
16 }

后台线程sumCalculate.js代码:

1 onmessage = function(event) {
2     var result = event.data * 10;
3     postMessage(result);
4 }

 

相关文章:

  • 2022-12-23
  • 2021-10-03
  • 2021-12-28
  • 2021-11-02
  • 2021-07-09
  • 2022-01-10
  • 2022-01-05
  • 2022-12-23
猜你喜欢
  • 2021-11-27
  • 2021-11-04
  • 2021-12-07
  • 2021-08-04
  • 2021-11-24
  • 2022-12-23
相关资源
相似解决方案