HTML5 API - Web Worker



웹 워커는 어플리케이션에서 백그라운드 프로세서를 사용할 수 있게 해주며, 기존 단일 레드에서 벗어나 멀티 레드를 통해 작업하는 것이 가능합니다.


하지만 워커는 DOM 전역 객체인 window 객체에 접근하지 못하며. 이는 곧 DOM에 접근하지 못한다는 말과 같습니다.


또한, 설계상 UI 작업(스레드)에 영향을 미치지는 않지만, 과도한 작업 시 CPU를 점유량 때문에 시스템 속도를 느리게 만듭니다.




1. 브라우저 지원현황:



브라우저 지원현황:

http://caniuse.com/#feat=webworkers



- 아래는 총 3개의 백그라운드 레드(워커)와 postMessage API를 연동하여 워커와 데이터를 주고받는 코드 예제 입니다.


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>postMessage</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //<![CDATA[
  9.  
  10.     var ws = {};
  11.    
  12.     function start(id) {
  13.  
  14.         (!ws[id] && window.Worker) && function () {
  15.            
  16.             //워커 생성
  17.             var w = ws[id] = new Worker('workers.js?2')
  18.  
  19.             // 워커 이벤트 핸들러 할당
  20.             bind(w, 'message', function (e) { document.getElementById(id).value = e.data; });
  21.             bind(w, 'error', function (e) { alert(e.message); });
  22.  
  23.             w.postMessage();
  24.         }();
  25.     };
  26.  
  27.     function terminate(id) {
  28.         // 워커 중지
  29.         ws[id].terminate();
  30.         delete ws[id];
  31.     };
  32.  
  33.     var init = (function (fn) {
  34.         fn('w1');
  35.         fn('w2');
  36.         fn('w3');
  37.     })(start);
  38.  
  39.     // 이벤트 할당
  40.     function bind(elem, type, handler, capture) {
  41.         type = typeof type === 'string' && type || '';
  42.         handler = handler || function () { ; };
  43.  
  44.         if (elem.addEventListener) {
  45.             elem.addEventListener(type, handler, capture);
  46.         }
  47.         else if (elem.attachEvent) {
  48.             elem.attachEvent('on' + type, handler);
  49.         }
  50.  
  51.         return elem;
  52.     };
  53.  
  54.  
  55. //]]>
  56. </script>
  57. <input id="w1" style="width:300px" />
  58. <input id="w2" style="width:300px" />
  59. <input id="w3" style="width:300px" /><br />
  60. <input type="button" name="w1" value="woker1Start" onclick="start(this.name)" />
  61. <input type="button" name="w1" value="woker1Stop" onclick="terminate(this.name)" /><br />
  62. <input type="button" name="w2" value="woker2Start" onclick="start(this.name)" />
  63. <input type="button" name="w2" value="woker2Stop" onclick="terminate(this.name)" /><br />
  64. <input type="button" name="w3" value="woker3Start" onclick="start(this.name)" />
  65. <input type="button" name="w3" value="woker3Stop" onclick="terminate(this.name)" />
  66. </body>
  67. </html>




참고 사이트:


webWorker API:

http://www.slideshare.net/jidolstar/html5-web-worker