Web Workers是Web内容在后台线程中运行脚本的简单方法。工做线程能够在不干扰用户界面的状况下执行任务。此外,它们可使用I / O执行XMLHttpRequest(尽管responseXML和channel属性始终为null)。建立后,工做人员能够经过将消息发布到该代码指定的事件处理程序(反之亦然),将消息发送到建立它的JavaScript代码。javascript
//判断浏览器是否支持Worker
if (window.Worker) {
const worker = new Worker('URL');
}
复制代码
if (window.Worker) {
try {
const worker = new Worker('URL');
worker.onerror = function(msg,fileName,lineno) {
throw msg;
}
} catch (err) {
return err;
}
}
复制代码
//msg can be an object, an array, or a string
let msg = {};
worker.postMessage(msg);
复制代码
worker.onmessage = function(e) {
console.log(e.data);
}
复制代码
// get data from html document
onmessage = function(e) {
console.log(e.data);
}
//catch err
onerror = function(err) {
console.log(err);
}
//some data
postMessage({});
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebWorker</title>
</head>
<body>
<button>开启计时器</button>
<span class="time"></span>
<script> document.querySelector('button') .addEventListener('click', function handleClick() { console.log('开启定时器......'); if (window.Worker) { const worker = new Worker('StartTimeLock.js'); worker.postMessage({msg: 'User:你好,我准备开启定时器了!', state: true}); worker.onmessage = function (e) { console.log(e.data.msg); document.querySelector('.time') .innerHTML = e.data.time; if (e.data.time === 10) { worker.terminate(); } }; } }, false); </script>
</body>
</html>
复制代码
onmessage = function (e) {
console.log(e.data.msg);
postMessage({msg:'Worker:Worker正在处理您的消息!!'});
if(e.data.state) {
let time = 0;
setInterval(function handleInterval() {
postMessage({time:time++});
},1000);
}
};
复制代码
我只是个“猥琐发育的大三银”,哪里写的不对还望大佬们海涵。html