본문 바로가기

[R]HTML5 웹 작업자(HTML5 Web Workers)

A web worker is a JavaScript running in the background, without affecting the performance of the page.

웹 작업자는 페이지의 성능에 영향을주지 않고 백그라운드에서 실행되는 JavaScript입니다.




What is a Web Worker?

웹 작업자 란 무엇입니까?


When executing scripts in an HTML page, the page becomes unresponsive until the script is finished.

HTML 페이지에서 스크립트를 실행할 때 스크립트가 끝날 때까지 페이지가 응답하지 않게됩니다.

A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. 

웹 작업자는 페이지의 성능에 영향을주지 않고 다른 스크립트와 독립적으로 백그라운드에서 실행되는 JavaScript입니다. 

You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

웹 작업자가 백그라운드에서 실행되는 동안 클릭, 선택 등 원하는 작업을 계속 수행 할 수 있습니다.




Browser Support

브라우저 지원


The numbers in the table specify the first browser version that fully support Web Workers.

표의 숫자는 웹 작업자를 완전히 지원하는 첫 번째 브라우저 버전을 지정합니다.


API

Web Storage

4.0

10.0

3.5

4.0

11.5




HTML Web Workers Example

HTML 웹 작업자 예제


The example below creates a simple web worker that count numbers in the background:

아래 예제는 백그라운드에서 숫자를 계산하는 간단한 웹 작업자를 만듭니다.


Example

Count numbers: 

Start Worker  Stop Worker





Check Web Worker Support

웹 워커 지원 확인


Before creating a web worker, check whether the user's browser supports it:

웹 작업자를 만들기 전에 사용자 브라우저가 웹 작업자를 지원하는지 확인하십시오.


1
2
3
4
5
6
if (typeof(Worker) !== "undefined") {
    // Yes! Web worker support!
    // Some code.....
} else {
    // Sorry! No Web Worker support..
}
cs




Create a Web Worker File

웹 작업자 파일 만들기


Now, let's create our web worker in an external JavaScript.

이제 웹 사이트 작업자를 외부 JavaScript로 만들어 보겠습니다.

Here, we create a script that counts. The script is stored in the "demo_workers.js" file:

여기서 우리는 중요한 스크립트를 만듭니다. 스크립트는 "demo_workers.js"파일에 저장됩니다.


1
2
3
4
5
6
7
8
9
var i = 0;
 
function timedCount() {
    i = i + 1;
    postMessage(i);
    setTimeout("timedCount()",500);
}
 
timedCount();
cs


The important part of the code above is the postMessage() method - which is used to post a message back to the HTML page.

위의 코드에서 중요한 부분은 postMessage()HTML 페이지에 메시지를 다시 게시하는 데 사용되는 메서드입니다.

Note: Normally web workers are not used for such simple scripts, but for more CPU intensive tasks.

참고 : 일반적으로 웹 작업자는 간단한 스크립트에는 사용되지 않지만 CPU 사용량이 많은 작업에는 사용됩니다.




Create a Web Worker Object

웹 작업자 개체 만들기


Now that we have the web worker file, we need to call it from an HTML page.

웹 작업자 파일이 생겼으므로 HTML 페이지에서 호출해야합니다.

The following lines checks if the worker already exists, if not - it creates a new web worker object and runs the code in "demo_workers.js":

다음 줄은 작업자가 이미 존재하는지 확인합니다. 그렇지 않으면 새 웹 작업자 객체를 만들고 "demo_workers.js"에서 코드를 실행합니다.


1
2
3
if (typeof(w) == "undefined") {
    w = new Worker("demo_workers.js");
}
cs


Then we can send and receive messages from the web worker.

그런 다음 웹 작업자에게 메시지를 보내고받을 수 있습니다.

Add an "onmessage" event listener to the web worker.

웹 작업자에게 "onmessage"이벤트 리스너를 추가하십시오.


1
2
3
w.onmessage = function(event){
    document.getElementById("result").innerHTML = event.data;
};
cs


When the web worker posts a message, the code within the event listener is executed. The data from the web worker is stored in event.data.

웹 작업자가 메시지를 게시하면 이벤트 리스너 내의 코드가 실행됩니다. 웹 작업자의 데이터는 event.data에 저장됩니다.




Terminate a Web Worker

웹 작업자 종료


When a web worker object is created, it will continue to listen for messages (even after the external script is finished) until it is terminated.

웹 작업자 객체가 생성되면 종료 될 때까지 외부 스크립트가 완료된 후에도 메시지를 수신 대기합니다.

To terminate a web worker, and free browser/computer resources, use the terminate() method:

웹 작업자를 종료하고 브라우저 / 컴퓨터 리소스를 확보하려면 다음 terminate()방법을 사용하십시오 .


1
w.terminate();
cs




Reuse the Web Worker

웹 작업자 재사용


If you set the worker variable to undefined, after it has been terminated, you can reuse the code:

worker 변수를 undefined로 설정하면 종료 된 후에 코드를 다시 사용할 수 있습니다.


1
w = undefined;
cs




Full Web Worker Example Code

전체 웹 작업자 예제 코드


We have already seen the Worker code in the .js file. Below is the code for the HTML page:

이미 .js 파일에서 Worker 코드를 보았습니다. 다음은 HTML 페이지의 코드입니다.


Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html>
<body>
 
<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button
<button onclick="stopWorker()">Stop Worker</button>
 
<script>
var w;
 
function startWorker() {
    if(typeof(Worker) !== "undefined") {
        if(typeof(w) == "undefined") {
            w = new Worker("demo_workers.js");
        }
        w.onmessage = function(event) {
            document.getElementById("result").innerHTML = event.data;
        };
    } else {
        document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
    }
}
 
function stopWorker() { 
    w.terminate();
    w = undefined;
}
</script>
 
</body>
</html>
cs





Web Workers and the DOM

웹 작업자와 DOM


Since web workers are in external files, they do not have access to the following JavaScript objects:

웹 작업자는 외부 파일에 있기 때문에 다음 JavaScript 객체에 액세스 할 수 없습니다.


The window object

윈도우 객체

The document object

문서 개체

The parent object

부모 객체