1.什么是 Web Worker?
当在 HTML 页面中执行脚本时,页面的状态是不可响应的,直到脚本已完成。
web worker 是运行在后台的 JavaScript,独立于其他脚本,不会影响页面的性能。您可以继续做任何愿意做的事情:点击、选取内容等等,而此时 web worker 在后台运行。
2.浏览器支持:
除了IE 其他主流浏览器均已支持。
3.小案例
index.html代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="wc">
<meta name="Keywords" content="web workers">
<meta name="Description" content="使用web workers demo">
<title>web workers</title>
</head>
<body>
<h2>web workers 测试</h2>
<lable for"username">用户名</lable>
<input type="text" id="username">
<input type="button" value="login" οnclick="helloYou()">
<hr>
<lable for"mynum">循环次数</lable>
<input type="number" id="mynum" min=0 value="100">
<input type="button" value="do sum" οnclick="sum()">
<hr>
</body>
<script>
<span style="white-space:pre"> </span>//浏览器兼容性判断
<span style="white-space:pre"> </span>window.οnlοad=function(){
<span style="white-space:pre"> </span>if(typeof(Worker)!=="undefined"){
<span style="white-space:pre"> </span>console.log("浏览器支持html5 web workers API");
<span style="white-space:pre"> </span>}else{
<span style="white-space:pre"> </span>alert("浏览器不支持html5 web workers API");
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>};
<span style="white-space:pre"> </span>//用户欢迎语
<span style="white-space:pre"> </span>function helloYou(){
<span style="white-space:pre"> </span>var myw=new Worker("worker.js");//创建一个web worker对象
<span style="white-space:pre"> </span>var uname=document.getElementById("username").value;
<span style="white-space:pre"> </span>myw.postMessage(uname);//向客户端后台发送数据
<span style="white-space:pre"> </span>//监听onmessage事件,如检测到该事件的触发,则获取客户端后台返回的数据
<span style="white-space:pre"> </span>myw.onmessage=function(event){
<span style="white-space:pre"> </span>alert(event.data);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>//循环求和 用大数据测试效果明显
<span style="white-space:pre"> </span>function sum(){
<span style="white-space:pre"> </span>var w=new Worker("worker.js");<span style="font-family: Verdana, Arial, 宋体;">//创建一个web worker对象</span>
<span style="white-space:pre"> </span>var num=document.getElementById("mynum").value;
<span style="white-space:pre"> </span>w.postMessage(num);
<span style="white-space:pre"> </span>w.onmessage=function(event){
<span style="white-space:pre"> </span>alert("1+...+"+num+"的和为:"+event.data);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
</script>
</html>
worker.js代码:
onmessage=function(event){
if(isNaN(event.data)){//功能1:返回字符串提示语
postMessage("welcome "+event.data+",你知道吗?web worker 是运行在后台的 JavaScript,不会影响页面的性能。");
}
else{//功能2:返回计算到某个数的和
var n=event.data;
var total=0;
for(var i=1;i<=n;i++){
total+=i;
}
postMessage(total);
}
}
web workers 主要运用于对cpu占用较高的运算或逻辑处理,它的好处是:它运行在后台的 JavaScript,独立于其他脚本,不会影响页面的性能。您可以继续做任何愿意做的事情:点击、选取内容等等,而此时 web worker 在后台运行。