(原)Html5之WebWorker Api详解(网页中多线程)
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- <script type="text/javascript">
- window.onload = function() {
- var worker = new Worker("render-task.js");
- worker.onmessage = function(event) {
- alert(eval(event.data).result);
- };
- worker.postMessage('({content: "Test", command: ' + writeMessage + '})');
- };
- function writeMessage() {
- var count = 0;
- while(count <= 9999999) {
- count++;
- }
- count++;
- return count;
- }
- </script>
- </head>
- <body>
- </body>
- </html>
接下来插入线程文件:
- onmessage = function(event) {
- var message = eval(event.data);
- message.text = "Response";
- var result = message.command();
- postMessage('({text: "Response", result:' + result + '})');
- };
根据测试:
1:线程文件中不可以使用document等BOM
2:线程文件中不可以使用调用地点的外部变量。
3:线程文件中可以调用调用地点的函数。但是必须通过json传递过来
4:线程文件中不可以有挂起的操作命令(alert等)
基本的数据调用传递流程
work.postMessage->线程的onmessage被触发
线程的onmessage文件内调用postMessage->work.onmessage被触发