HTML5 API - Web Worker
HTML5 2012. 5. 21. 16:12
웹 워커는 어플리케이션에서 백그라운드 프로세서를 사용할 수 있게 해주며, 기존 단일 스레드에서 벗어나 멀티 스레드를 통해 작업하는 것이 가능합니다.
하지만 워커는 DOM 전역 객체인 window 객체에 접근하지 못하며. 이는 곧 DOM에 접근하지 못한다는 말과 같습니다.
또한, 설계상 UI 작업(스레드)에 영향을 미치지는 않지만, 과도한 작업 시 CPU를 점유량 때문에 시스템 속도를 느리게 만듭니다.
1. 브라우저 지원현황:
브라우저 지원현황:
http://caniuse.com/#feat=webworkers
- 아래는 총 3개의 백그라운드 스레드(워커)와 postMessage API를 연동하여 워커와 데이터를 주고받는 코드 예제 입니다.
-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
<html xmlns="http://www.w3.org/1999/xhtml">
-
<head>
-
<title>postMessage</title>
-
</head>
-
<body>
-
<script type="text/javascript">
-
//<![CDATA[
-
-
var ws = {};
-
-
function start(id) {
-
-
(!ws[id] && window.Worker) && function () {
-
-
//워커 생성
-
var w = ws[id] = new Worker('workers.js?2')
-
-
// 워커 이벤트 핸들러 할당
-
bind(w, 'message', function (e) { document.getElementById(id).value = e.data; });
-
bind(w, 'error', function (e) { alert(e.message); });
-
-
w.postMessage();
-
}();
-
};
-
-
function terminate(id) {
-
// 워커 중지
-
ws[id].terminate();
-
delete ws[id];
-
};
-
-
var init = (function (fn) {
-
fn('w1');
-
fn('w2');
-
fn('w3');
-
})(start);
-
-
// 이벤트 할당
-
function bind(elem, type, handler, capture) {
-
type = typeof type === 'string' && type || '';
-
handler = handler || function () { ; };
-
-
if (elem.addEventListener) {
-
elem.addEventListener(type, handler, capture);
-
}
-
else if (elem.attachEvent) {
-
elem.attachEvent('on' + type, handler);
-
}
-
-
return elem;
-
};
-
-
-
//]]>
-
</script>
-
<input id="w1" style="width:300px" />
-
<input id="w2" style="width:300px" />
-
<input id="w3" style="width:300px" /><br />
-
<input type="button" name="w1" value="woker1Start" onclick="start(this.name)" />
-
<input type="button" name="w1" value="woker1Stop" onclick="terminate(this.name)" /><br />
-
<input type="button" name="w2" value="woker2Start" onclick="start(this.name)" />
-
<input type="button" name="w2" value="woker2Stop" onclick="terminate(this.name)" /><br />
-
<input type="button" name="w3" value="woker3Start" onclick="start(this.name)" />
-
<input type="button" name="w3" value="woker3Stop" onclick="terminate(this.name)" />
-
</body>
-
</html>
참고 사이트:
webWorker API:
http://www.slideshare.net/jidolstar/html5-web-worker