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:
- //worker.js
- onmessage =function (evt){
- var d = evt.data;//Get the data sent through evt.data
- postMessage( d );//Send the obtained data to the main thread
- }
HTML page: test.html
- HTML>
- html>
- 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>>
- meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
- 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>">
- //WEB页主线程
- var worker =new Worker("worker.js"); //创建一个Worker对象并向它传递将在新线程中执行的脚本的URL
- worker.postMessage("hello world"); //向worker发送数据
- 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>
- 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发送来的数据
- }
- script>
- head>
- body>body>
- 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:
- var fibonacci =function(n) {
- return n
- };
- //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:
- //fibonacci.js
- varfibonacci =function(n) {
- return n
- };
- onmessage =function(event) {
- var n = parseInt(event."width: auto; height: auto; float: none;" id="16_nwp">"text-decoration: none;" mpid="16" target="_blank" ref="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=0601 1078_cpr&rb=0&rs=1&seller_id=1&sid =45fdcf1cab219561&ssp2=1&time=0&t=tpclicked3_hc&tu=u1922429&u=http://www.admin10000.com/document/1183.html&url=0" id="16_nwl">"color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">data, 10);
- postMessage(fibonacci(n));
- };
HTML Open:fibonacci.html
- HTML>
- html>
- 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>>
- meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
- title>web worker fibonaccititle>
- 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>">
- onload =function(){
- var worker =new Worker('fibonacci.js');
- worker.addEventListener('message', function(event) {
- var timer2 = (new Date()).valueOf();
- 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 ) );
- }, false);
- var timer = (new Date()).valueOf();
- console.log('开始计算:40','时间:' timer );
- setTimeout(function(){
- 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() );
- },1000);
- worker.postMessage(40);
- console.log('我在计算数列的时候执行了', '时间:' (new Date()).valueOf() );
- }
- script>
- 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>>
- body>
- body>
- html>
在Chrome中打开fibonacci.html,控制台得到如下输出:
开始计算:40 时间:1316508212705
我在计算数列的时候执行了 时间:1316508212734
定时器
- 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数据
- // /aj/webWorker/core.js
- function $E(id) {
- return document.getElementById(id);
- }
- onload =function() {
- //通过web worker加载
- $E('workerLoad').onclick =function() {
- var url ='http://js.wcdn.cn/aj/mblog/face2';
- var d = (new Date()).valueOf();
- var worker =new Worker(url);
- worker.onmessage =function(obj) {
- console.log('web worker: ' ((new Date()).valueOf() - d));
- };
- };
- //通过jsonp加载
- $E('jsonpLoad').onclick =function() {
- var url ='http://js.wcdn.cn/aj/mblog/face1';
- var d = (new Date()).valueOf();
- STK.core.io.scriptLoader({
- method:'post',
- url : url,
- onComplete : function() {
- console.log('jsonp: ' ((new Date()).valueOf() - d));
- }
- });
- };
- //通过ajax加载
- $E('ajaxLoad').onclick =function() {
- var url ='http://js.wcdn.cn/aj/mblog/face';
- var d = (new Date()).valueOf();
- STK.core.io.ajax({
- url : url,
- onComplete : function(json) {
- console.log('ajax: ' ((new Date()).valueOf() - d));
- }
- });
- };
- };
HTML页面:/aj/webWorker/worker.html
- HTML>
- html>
- 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>>
- meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
- 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>
- 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>
- script type="text/javascript" src="http://js.wcdn.cn/aj/webWorker/core.js">script>
- head>
- body>
- input type="button" id="workerLoad" value="web worker加载">input>
- input type="button" id="jsonpLoad" value="jsonp加载">input>
- 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>
- body>
- html>
设置HOST
通过 http://js.wcdn.cn/aj/webWorker/worker.html 访问页面然后分别通过三种方式加载数据,得到控制台输出:
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

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version
God-level code editing software (SublimeText3)
