Home > Web Front-end > H5 Tutorial > body text

Web Worker usage guide for HTML5_html5 tutorial tips

WBOY
Release: 2016-05-16 15:46:23
Original
1240 people have browsed it

Web Workers is a javascript multi-threading solution provided by HTML5. We can hand over some computationally intensive code to web workers to run without freezing the user interface.
1: How to use Worker

The basic principle of Web Worker is to use the Worker class to load a javascript file in the current main thread of javascript to open a new thread, which has the effect of non-blocking execution and provides data between the main thread and the new thread. Exchanged interfaces: postMessage, onmessage.

So how to use it, let’s look at an example:

JavaScript CodeCopy content to clipboard
  1. //worker.js
  2. onmessage =function (evt){
  3. var d = evt.data;//Get the data sent through evt.data
  4. postMessage( d );//Send the obtained data to the main thread
  5. }

HTML page: test.html


XML/HTML CodeCopy content to clipboard
  1. >  
  2. <html>  
  3. <<span style="width: auto; height: auto; float: none;" id="20_nwp"><a style="text-decoration: none;" mpid="20" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=619521ab1ccffd45&k=head&k0=head&kdi0=0&luki=6&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=45fdcf1cab219561&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/1183.html&urlid=0" id="20_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">headspan>a>span>>  
  4.  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>  
  5.  <script type="text/<span style="width: auto; height: auto; float: none;" id="21_nwp"><a style="text-decoration: none;" mpid="21" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=619521ab1ccffd45&k=javascript&k0=javascript&kdi0=0&luki=9&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=45fdcf1cab219561&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/1183.html&urlid=0" id="21_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">javascriptspan>a>span>">  
  6. //WEB页主线程   
  7. var worker =new Worker("worker.js"); //创建一个Worker对象并向它传递将在新线程中执行的脚本的URL   
  8.  worker.postMessage("hello world");     //向worker发送数据   
  9.  worker.onmessage =function(evt){     //接收worker传过来的数据<span style="width: auto; height: auto; float: none;" id="22_nwp"><a style="text-decoration: none;" mpid="22" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=619521ab1ccffd45&k=����&k0=����&kdi0=0&luki=2&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=45fdcf1cab219561&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/1183.html&urlid=0" id="22_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">函数span>a>span>  
  10.    console.log(evt.<span style="width: auto; height: auto; float: none;" id="23_nwp"><a style="text-decoration: none;" mpid="23" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=619521ab1ccffd45&k=data&k0=data&kdi0=0&luki=4&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=45fdcf1cab219561&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/1183.html&urlid=0" id="23_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">dataspan>a>span>);              //输出worker发送来的数据   
  11.  }
  12. script>
  13. head>
  14. <body>body>
  15. html>

After opening test.html with Chrome browser, the console outputs "hello world", indicating that the program execution is successful.

Through this example we can see that using web workers is mainly divided into the following parts

WEB main thread:

1. Load a JS file through worker = new Worker( url ) to create a worker and return a worker instance.

 2. Send data to the worker through the worker.postMessage(data) method.

3. Bind the worker.onmessage method to receive the data sent by the worker.

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

Worker new thread:

 1. Send data to the main thread through the postMessage(data) method.

 2. Bind the onmessage method to receive the data sent by the main thread.
2: What can Worker do

Now that we know how to use web worker, what is its use and what problems can it help us solve. Let's look at an example of the fibonacci sequence.

Everyone knows that in mathematics, the fibonacci sequence is defined recursively: F0=0, F1=1, Fn=F(n-1) F(n-2) (n>=2, n∈N* ), and the common implementation of javascript is:

JavaScript CodeCopy content to clipboard
  1. var fibonacci =function(n) {
  2. return n <2? n : arguments.callee(n -1) arguments.callee(n -2);
  3. };
  4. //fibonacci(36)

Using this method in Chrome to execute the fibonacci sequence of 39 takes 19097 milliseconds, but when it comes to calculating 40, the browser directly prompts that the script is busy.

Since JavaScript is executed in a single thread, the browser cannot execute other JavaScript scripts during the process of calculating the sequence, and the UI rendering thread will also be suspended, causing the browser to enter a zombie state. Using a web worker to put the calculation process of the sequence into a new thread will avoid this situation. See the example specifically:

JavaScript CodeCopy content to clipboard

  HTML Open:fibonacci.html

XML/HTML CodeInternational Code Configuration
  1. >  
  2. <html>  
  3. <<span style="width: auto; height: auto; float: none;" id="11_nwp"><a style="text-decoration: none;" mpid="11" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=619521ab1ccffd45&k=head&k0=head&kdi0=0&luki=6&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=45fdcf1cab219561&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/1183.html&urlid=0" id="11_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">headspan>a>span>>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>  
  5. <title>web worker fibonaccititle>  
  6. <script type="text/<span style="width: auto; height: auto; float: none;" id="12_nwp"><a style="text-decoration: none;" mpid="12" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=619521ab1ccffd45&k=javascript&k0=javascript&kdi0=0&luki=9&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=45fdcf1cab219561&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/1183.html&urlid=0" id="12_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">javascriptspan>a>span>">  
  7.   onload =function(){   
  8.       var worker =new Worker('fibonacci.js');     
  9.       worker.addEventListener('message', function(event) {   
  10.         var timer2 = (new Date()).valueOf();   
  11.            console.log( '结果:' event.<span style="width: auto; height: auto; float: none;" id="13_nwp"><a style="text-decoration: none;" mpid="13" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=619521ab1ccffd45&k=data&k0=data&kdi0=0&luki=4&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=45fdcf1cab219561&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/1183.html&urlid=0" id="13_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">dataspan>a>span>, '时间:'  timer2, '用时:'  ( timer2  - timer ) );   
  12.       }, false);   
  13.       var timer = (new Date()).valueOf();   
  14.       console.log('开始计算:40','时间:'  timer );   
  15.       setTimeout(function(){   
  16.           console.log('定时器<span style="width: auto; height: auto; float: none;" id="14_nwp"><a style="text-decoration: none;" mpid="14" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=619521ab1ccffd45&k=����&k0=����&kdi0=0&luki=2&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=45fdcf1cab219561&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/1183.html&urlid=0" id="14_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">函数span>a>span>在计算数列时执行了', '时间:'  (new Date()).valueOf() );   
  17.       },1000);   
  18.       worker.postMessage(40);   
  19.       console.log('我在计算数列的时候执行了', '时间:'  (new Date()).valueOf() );   
  20.   }     
  21.   script>  
  22. <span style="width: auto; height: auto; float: none;" id="15_nwp"><a style="text-decoration: none;" mpid="15" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=619521ab1ccffd45&k=head&k0=head&kdi0=0&luki=6&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=45fdcf1cab219561&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/1183.html&urlid=0" id="15_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">headspan>a>span>>  
  23. <body>  
  24. body>  
  25. html>  

  在Chrome中打开fibonacci.html,控制台得到如下输出:
 
开始计算:40 时间:1316508212705
我在计算数列的时候执行了 时间:1316508212734
定时器

XML/HTML Code复制内容到剪贴板
  1. <span style="width: auto; height: auto; float: none;" id="9_nwp"><a style="text-decoration: none;" mpid="9" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=619521ab1ccffd45&k=����&k0=����&kdi0=0&luki=2&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=45fdcf1cab219561&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/1183.html&urlid=0" id="9_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">函数span>a>span>  

在计算数列时执行了 时间:1316508213735
结果:102334155 时间:1316508262820 用时:50115

  这个例子说明在worker中执行的fibonacci数列的计算并不会影响到主线程的代码执行,完全在自己独立的线程中计算,只是在计算完成之后将结果发回主线程。

  利用web worker我们可以在前端执行一些复杂的大量运算而不会影响页面的展示,并且不会弹出恶心的脚本正忙提示。

  下面这个例子使用了web worker来计算场景中的像素,场景打开时是一片一片进行绘制的,一个worker只计算一块像素值。

  http://nerget.com/rayjs-mt/rayjs.html
  三:Worker的其他尝试

  我们已经知道Worker通过接收一个URL来创建一个worker,那么我们是否可以利用web worker来做一些类似jsonp的请求呢,大家知道jsonp是通过插入script标签来加载json数据的,而script元素在加载和执行过程中都是阻塞式的,如果能利用web worker实现异步加载将会非常不错。

  下面这个例子将通过 web worker、jsonp、ajax三种不同的方式来加载一个169.42KB大小的JSON数据

 

JavaScript Code复制内容到剪贴板
  1. // /aj/webWorker/core.js   
  2. function $E(id) {   
  3.     return document.getElementById(id);   
  4. }   
  5. onload =function() {   
  6.     //通过web worker加载   
  7.     $E('workerLoad').onclick =function() {   
  8.         var url ='http://js.wcdn.cn/aj/mblog/face2';   
  9.         var d = (new Date()).valueOf();   
  10.         var worker =new Worker(url);   
  11.         worker.onmessage =function(obj) {   
  12.             console.log('web worker: '  ((new Date()).valueOf() - d));   
  13.         };   
  14.     };   
  15.     //通过jsonp加载   
  16.     $E('jsonpLoad').onclick =function() {   
  17.         var url ='http://js.wcdn.cn/aj/mblog/face1';   
  18.         var d = (new Date()).valueOf();   
  19.         STK.core.io.scriptLoader({   
  20.             method:'post',   
  21.             url : url,   
  22.             onComplete : function() {   
  23.                 console.log('jsonp: '  ((new Date()).valueOf() - d));   
  24.             }   
  25.         });   
  26.     };   
  27.     //通过ajax加载   
  28.     $E('ajaxLoad').onclick =function() {   
  29.         var url ='http://js.wcdn.cn/aj/mblog/face';   
  30.         var d = (new Date()).valueOf();   
  31.         STK.core.io.ajax({   
  32.             url : url,   
  33.             onComplete : function(json) {   
  34.                 console.log('ajax: '  ((new Date()).valueOf() - d));   
  35.             }   
  36.         });   
  37.     };   
  38. };  

  HTML页面:/aj/webWorker/worker.html

 

XML/HTML Code复制内容到剪贴板
  1. >  
  2. <html>  
  3. <<span style="width: auto; height: auto; float: none;" id="4_nwp"><a style="text-decoration: none;" mpid="4" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=619521ab1ccffd45&k=head&k0=head&kdi0=0&luki=6&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=45fdcf1cab219561&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/1183.html&urlid=0" id="4_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">headspan>a>span>>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>  
  5. <title>Worker example: load <span style="width: auto; height: auto; float: none;" id="5_nwp"><a style="text-decoration: none;" mpid="5" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=619521ab1ccffd45&k=data&k0=data&kdi0=0&luki=4&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=45fdcf1cab219561&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/1183.html&urlid=0" id="5_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">dataspan>a>span>title>  
  6. <script src="http://js.t.sinajs.cn/STK/js/gaea.1.14.js" type="text/<span style="width: auto; height: auto; float: none;" id="6_nwp"><a style="text-decoration: none;" mpid="6" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=619521ab1ccffd45&k=javascript&k0=javascript&kdi0=0&luki=9&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=45fdcf1cab219561&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/1183.html&urlid=0" id="6_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">javascriptspan>a>span>">script>  
  7. <script type="text/javascript" src="http://js.wcdn.cn/aj/webWorker/core.js">script>  
  8. head>  
  9. <body>  
  10.     <input type="button" id="workerLoad" value="web worker加载">input>  
  11.     <input type="button" id="jsonpLoad" value="jsonp加载">input>  
  12.     <input type="button" id="<span style="width: auto; height: auto; float: none;" id="7_nwp"><a style="text-decoration: none;" mpid="7" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=619521ab1ccffd45&k=ajax&k0=ajax&kdi0=0&luki=8&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=45fdcf1cab219561&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/1183.html&urlid=0" id="7_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">ajaxspan>a>span>Load" value="ajax加载">input>  
  13. body>  
  14. html>  

  设置HOST
 

复制代码
代码如下:
127.0.0.1 js.wcdn.cn 

  通过 http://js.wcdn.cn/aj/webWorker/worker.html 访问页面然后分别通过三种方式加载数据,得到控制台输出:
 

复制代码
代码如下:
web worker: 174
jsonp: 25
ajax: 38

After trying several times, I found that the time to load data through jsonp and ajax is not much different, and the loading time of web worker has always been at a high level, so using web worker to load data is still relatively slow, even with large amounts of data. There is no advantage. It may be that it takes time for Worker to initialize new threads. There is no advantage other than being non-blocking during loading.

So can web worker support cross-domain js loading? This time we access the page through http://127.0.0.1/aj/webWorker/worker.html. When clicking the "web worker loading" loading button, Chrome will download There is no response, and an error is prompted under FF6. From this we can know that web worker does not support cross-domain loading of JS, which is bad news for websites that deploy static files to a separate static server.

So web worker can only be used to load json data in the same domain, but ajax can already do this, and it is more efficient and versatile. Let the Worker do what it is good at.
Four: Summary

Web workers look nice, but they are full of devils.

What we can do:

1. You can load a JS to perform a large number of complex calculations without hanging the main process, and communicate through postMessage, onmessage

2. You can load additional script files in the worker through importScripts(url)

 3. You can use setTimeout(), clearTimeout(), setInterval(), and clearInterval()

4. You can use XMLHttpRequest to send requests

5. Can access some properties of navigator

What are the limitations:

1. Cannot load JS across domains

 2. The code within the worker cannot access the DOM

3. The implementation of Worker in various browsers is not consistent. For example, FF allows the creation of new workers in workers, but Chrome does not allow it.

 4. Not every browser supports this new feature

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!