专栏首页游戏杂谈HTML5的Web Workers

HTML5的Web Workers

该特性仅支持:FF3.5+、Opera 10.6+、Chrome 3+、Safari 4。

详情请参数(下面的参考链接中都有例子说明):

https://developer.mozilla.org/En/Using_web_workers

https://developer.mozilla.org/En/DOM/Worker

http://www.whatwg.org/specs/web-workers/current-work/

中文:WEB Workers提升WEB前端脚本JavaScript的处理性能

这里以一个计算加法和乘法为例:

1、创建一个worker

2、worker使用postMessage方法,发送请求,在处理时再通过postMessage返回给消息给创建者,它的onmessage方法会捕获进行处理

3、如果需要kill worker直接使用terminate方法

最终运行的界面 :

完整html代码

<!DOCTYPE html>
<html>
 <head>
  <title>HTML5__Web Workers(仅支持FF3.5+、Opera 10.6+、Chrome 3+、Safari 4)</title>
  <meta name="generator" content="editplus" />
  <meta name="author" content="" />
  <meta name="keywords" content="" />
  <meta name="description" content="" />
  <meta http-equiv="content-type" content="text/html;charset=utf-8">
  <link rel="stylesheet" type="text/css" href="http://www.codediesel.com/demos/workers/view.css" />
 </head>

 <body id="main_body">
  
<img id="top" src="http://www.codediesel.com/demos/workers/top.png" alt=""> 
<div id="form_container"> 
    <h1><a>Untitled Form</a></h1> 
    <form id="main" class="appnitro"  method="post" action=""> 
        <div class="form_description"> 
            <h2 id="title"></h2> 
        </div>                        
        <ul > 
            <li id="li_2" > 
                <label class="description" for="element_2">X </label> 
                <div> 
                    <input id="x" name="x" class="element text medium" type="text" maxlength="255" value="3"/> 
                </div> 
            </li>
            <li id="li_3" > 
                <label class="description" for="element_3">Y </label> 
                <div> 
                    <input id="y" name="y" class="element text medium" type="text" maxlength="255" value="3"/> 
                </div> 
            </li>        
            <li id="li_1" > 
                <label class="description" for="element_1">Messages </label> 
                <div> 
                    <textarea id="output" name="output" class="element textarea medium"></textarea> 
                </div> 
            </li> 
            <li class="buttons"> 
                <input type="hidden" name="form_id" value="87137" /> 
                <input id="addButton" class="button_text" type="button" value="Add" /> 
                <input id="multButton" class="button_text" type="button"  value="Multiply" /> 
                <input id="killButton" class="button_text" type="button" value="Stop Worker" /> 
                <input id="clearBtn" class="button_text" type="button" value="Clear" /> 
            </li> 
        </ul> 
    </form>    
    <div id="footer"></div> 
</div> 
<img id="bottom" src="http://www.codediesel.com/demos/workers/bottom.png" alt=""> 

<script type='text/javascript'>   1:     2:     3: !(function() {   4:        5:     6:     var getWebWorkerSupport = function() {   7:         return (typeof(Worker) !== "undefined") ? true:false;   8:     }   9:    10:     var getElem = function(id) {  11:         return typeof id === 'string' ? document.getElementById(id) : id;  12:     }  13:    14:     var worker,  15:         isSupport = getWebWorkerSupport();  16:    17:    18:     if (isSupport) {  19:           20:         var createWorker = function() {  21:             if (worker) {  22:                 return ;  23:             }  24:    25:             worker = new Worker("worker.js");  26:             worker.onmessage = function(evt) {  27:                 getElem("output").value += evt.data + '\n';  28:             }  29:             worker.onerror = function(evt) {  30:                 getElem("output").value += "\n在第["+ evt.lineno +"]行发生错误: " + evt.message;  31:             }  32:         }  33:    34:         getElem("multButton").onclick = function() {  35:             createWorker();  36:    37:             var x = document.getElementById("x").value;  38:             var y = parseFloat(document.getElementById("y").value);  39:    40:             var str = "mult_" + x + "_" + y;  41:               42:             worker.postMessage(str);  43:         }  44:           45:         getElem("addButton").onclick = function() {  46:             createWorker();  47:    48:             var x = document.getElementById("x").value;  49:             var y = parseFloat(document.getElementById("y").value);  50:    51:             var str = "add_" + x + "_" + y;  52:             worker.postMessage(str);  53:         }  54:    55:         getElem("killButton").onclick = function() {  56:             if (worker) {  57:                 worker.terminate();  58:                 worker = null;  59:             }  60:         }  61:     } else {  62:         getElem("multButton").disabled = getElem("addButton").disabled = getElem("killButton").disabled = true;  63:     }  64:    65:     getElem("title").innerHTML = "您当前使用的浏览器"+(isSupport ? "支持" : "<em class='error'>不支持</em>")+"Web Worker";  66:    67:     getElem("clearBtn").onclick = function() {  68:         getElem("output").value = "";  69:     }  70: })();</script>

 </body>
</html>

worker.js的代码:

unction addNumbers(x,y) {
   return x + y;


unction mulNumbers(x,y) {
   return x*y;


his.onmessage = function (event) {
   var msg = event.data,
       arr = msg.split("_"),
       op = arr[0],
       x = (arr[1] || "")|0,
       y = (arr[2] || "")|0;

   switch(op) {
       case 'mult':
           postMessage( x + "*" + y + "=" + mulNumbers(x, y));
           break;
       case 'add':
           postMessage( x + "+" + y + "=" + addNumbers(x, y));
           break;
       default:
           postMessage("Wrong operation specified");
   }

   var i = 1;
   while (i < 1000*1000*1000) {
       if (i % 500000 === 0) {
           postMessage(i);
       }
       i++;
   }

;

本章参考自:http://www.codediesel.com/demos/workers/     (有部分修改)

点些直接下载本文示例代码>>

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Lua游戏开发参考资料收集

    What is a good game engine that uses Lua? [closed]

    meteoric
  • flex+php截图Demo

    一、直接将byteArray转为bitmap通过loader(flash.display.Loader)显示在舞台上;

    meteoric
  • AS3给图片加水印文字

    通过FileReference获取选中的图片,调用它的load方法,将图片存入到内存中。使用Loader(flash.display.Loader)类的loa...

    meteoric
  • jQuery

    jQuery是目前使用最广泛的javascript函数库。据统计,全世界排名前100万的网站,有46%使用jQuery,远远超过其他库。微软公司甚至把jQuer...

    py3study
  • EngineerCMS核心代码

    版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hotqin888/article/det...

    hotqin888
  • 专栏:014:客官,你要的实战我给你.

    谢伟
  • Servlet与Jsp的结合使用实现信息管理系统二

    PS:前面说了抽取框架的搭建,接着就要我们开始进入网址的时候就要查到全部信息并显示在首页,我们用到的MySql数据库,具体步骤是: 创建数据库,创建表,添加信息...

    cMusketeer
  • Angular ng-class的小细节

     在前面Angularjs开发一些经验总结中我们说到在angular开发中angular controller never 包含DOM元素(html/css),...

    javascript.shop
  • bootstrap模态框之加载页面至modal-boby

    思路:使用$("#reserveForm").html(result); result为Ajax请求controller所返回的页面

    week
  • ztree实现左边动态生成树,右边为具体信息功能

    王小婷

扫码关注云+社区

领取腾讯云代金券