看Web Workers的时候遇到谷歌报错:
主页js代码是
var workers = new Worker(‘webserver.js‘); workers.onmessage = function(evt) { alert(evt.data); } workers.postMessage(‘‘);
webserver.js代码是
onmessage = function(evt) { postMessage(2333); }
Firefox和IE10运行没有问题,在Stack Overflow上找到了解决方法:http://stackoverflow.com/questions/21408510/chrome-cant-load-web-worker
将webserver.js内容改为
function worker_function() { //这里写原本在webserver.js里的代码 onmessage = function(evt) { postMessage(2333); } } if(window!=self) worker_function();
<script type="text/javascript" src="webserver.js"></script>的方式插入主页面,将var workers = new Worker(‘webserver.js‘)改为:
var workers = new Worker(URL.createObjectURL(new Blob(["("+worker_function.toString()+")()"], {type: ‘text/javascript‘})));
总之是解决了,但不知道原理,暂时做条记录。
时间: 2024-10-15 12:10:30