3
定義我寫了3個文件來測試WebWorker,
webworker.html爲什麼工人不JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<table id="table"></table>
<script>
// var worker = new Worker('webworker3.1.js');
var worker = new Worker('webworker3.1.js');
worker.postMessage('');
worker.onmessage = function(event){
console.log(event.data);
if(event.data != ''){
var j, k, tr, td,
intArray = event.data.split(';'),
table = document.getElementById('table');
for(var i = 0; i < intArray.length; i++){
j = parseInt(i/10, 0);
k = i % 10;
if(k == 0){
tr = document.createElement('tr');
tr.id = 'tr' + j;
table.appendChild(tr);
}else{
tr = document.getElementById('tr' + j);
}
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = intArray[j * 10 + k];
td.style.backgroundColor = 'blue';
td.style.color = 'white';
td.width = '30';
}
}
};
</script>
</body>
</html>
這是顯示一個主HTML。
webworker3.1.js
onmessage = function(event){
var intArray = new Array(100);
for(var i = 0; i < 100; i++){
intArray[i] = parseInt(Math.random() * 100);
}
var worker = new Worker('webworker3.2.js');
worker.postMessage(JSON.stringify(intArray));
worker.onmessage = function(event){
postMessage(event.data);
}
}
這是主線程,我在其中創建一個子線程。 webworker3.2.js
onmessage = function(event){
var intArray = JSON.parse(event.data);
var returnStr = '';
for(var i = 0; i < intArray.length; i++){
if(parseInt(intArray[i] % 3) == 0){
if('' !== returnStr){
returnStr += ';';
}
returnStr += intArray[i];
}
}
postMessage(returnStr);
close();
}
當我在Chrome中打開webworker.html,它有一個錯誤:
webworker3.1.js:7 Uncaught ReferenceError: Worker is not defined
我找不到原因,誰可以告訴我嗎?
什麼是你的Chrome版本? –
43.0.2357.130 m – GerBawn