HTML5のWeb Worker
Web Worker简述
web worker 是运行在后台的 JavaScript,不会影响页面的性能。
使用步骤
1> 检查浏览器是否支持Web Worker
if (typeof Worker != "undefined") {
// support
} else {
// your browser does not support
}
2>创建Web Worker对象,执行后台任务
if (typeof worker == "undefined") {
worker = new Worker("task.js");
}
worker.onmessage = function(event) {
message = event.data;
detailSpan.innerHTML = message;
};
3> 终止Web Woker
function terminate() {
worker.terminate();
worker = undefined;
}
实例
使用按钮控制后台执行任务,html代码如下:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<noscript>Your browser does not support JavaScript pluin</noscript>
<script type="text/javascript">
var worker;
var message = "";
function start() {
var detailSpan = document.querySelector("#detail");
if (typeof Worker != "undefined") {
if (typeof worker == "undefined") {
worker = new Worker("task.js");
}
worker.onmessage = function(event) {
message = event.data;
detailSpan.innerHTML = message;
};
} else {
message = "Sorry, your browser does not support web workers.";
detailSpan.innerHTML = message;
}
}
function terminate() {
worker.terminate();
worker = undefined;
}
</script>
<style type="text/css">
#status {
width: 600px;
height: 200px;
border:#CCDD66 1px solid;
margin:0 auto;
}
#btns {
margin-top: 20px;
text-align: center;
}
</style>
</head>
<body>
<div id="status">
<h3>status</h3>
<span id="detail"></span>
</div>
<div id="btns">
<button type="button" onclick="start()">Start</button>
<button type="button" onclick="terminate()">Terminate</button>
</div>
</body>
</html>
task.js表示后台执行任务,代码如下:
var indexNumber = 0;
function timeCount() {
indexNumber += 1;
postMessage(indexNumber);
setTimeout("timeCount()", 500);
}
timeCount();