0Pricing
Web Performance Optimization & Lighthouse · 강의

웹 워커와 메인 스레드 분리

계산량이 많은 작업을 웹 워커로 넘겨 메인 스레드를 여유롭게 유지하고 반응성을 확보하는 방법을 이해합니다.

웹 워커와 메인 스레드 분리은(는) CoddyKit의 무료 Web Performance Optimization & Lighthouse 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Web Performance Optimization & Lighthouse 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Web Performance Optimization & Lighthouse 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Unblocking the Main Thread

When you interact with a website, everything you see and click is handled by the browser's main thread. This thread is like a single lane highway for all your JavaScript code, UI updates, and event handling.

If a heavy task runs on this main thread, it can block everything else, making your website freeze and feel unresponsive. This is where Web Workers come in!

Understanding the Main Thread

The main thread is crucial for a smooth user experience. It's responsible for:

  • Parsing HTML and CSS
  • Executing JavaScript
  • Handling user events (clicks, scrolls)
  • Updating the user interface (rendering pixels)

Because JavaScript is single-threaded in the browser, a long-running script on the main thread will pause all these activities, leading to a 'frozen' UI.

Introducing Web Workers

Web Workers allow you to run scripts in the background, in a separate thread, without interfering with the main execution thread of the browser. Think of it as giving your browser an extra lane on the highway for heavy traffic.

  • They perform tasks off the main thread.
  • They keep the UI responsive during intensive operations.
  • They communicate with the main thread by sending messages.

Worker Types: Dedicated & More

There are a few types of Web Workers, but the most common and what we'll focus on are Dedicated Workers.

  • Dedicated Workers: Used by a single script. Each instance is tied to one main thread script.
  • Shared Workers: Can be accessed by multiple scripts, even from different windows/iframes.
  • Service Workers: Used for advanced features like offline experiences, caching, and push notifications (a more specialized type).

Spawning a New Worker

Creating a dedicated Web Worker is straightforward. You instantiate a Worker object, passing the URL of the script that the worker will execute.

This worker script runs in its own isolated global context.

const myWorker = new Worker('myWorker.js');

console.log('Worker created!');

Sending Data to a Worker

The main thread communicates with a worker using the postMessage() method. This method sends a message (which can be a string, JSON object, or other data) to the worker.

The data is copied, not shared, between the main thread and the worker.

const myWorker = new Worker('myWorker.js');

myWorker.postMessage({ type: 'startCalculation', data: 1000000 });
console.log('Message sent to worker!');

Receiving Worker Messages

To get results or updates from a worker, the main thread listens for the message event on the worker object. The data sent by the worker is available in event.data.

Similarly, the worker script itself listens for messages using self.onmessage.

const myWorker = new Worker('myWorker.js');

myWorker.onmessage = function(event) {
  console.log('Result from worker:', event.data);
};

myWorker.postMessage('Start work!');

Inside the Worker Script

The script loaded by the worker runs in its own isolated environment. It doesn't have direct access to the DOM or the window object, but it has its own global scope, represented by self.

The worker sends messages back to the main thread using self.postMessage().

// myWorker.js (the worker's script)
self.onmessage = function(event) {
  const receivedData = event.data;
  console.log('Worker received:', receivedData);

  // Perform a task
  const result = receivedData + ' processed!';

  // Send result back to the main thread
  self.postMessage(result);
};

Runnable Demo: Heavy Work Offloaded

Here's a demo using a Web Worker to perform a heavy calculation. Observe how the main thread remains responsive (simulated by log messages) while the worker does its job.

First, here's the content for worker.js that performs a sum:

// worker.js
self.onmessage = function(event) {
  let sum = 0;
  const limit = event.data; // Expecting a number
  console.log('Worker: Starting calculation for limit:', limit);
  for (let i = 0; i < limit; i++) {
    sum += i; // A computationally heavy loop
  }
  self.postMessage(sum);
  console.log('Worker: Calculation finished and result sent.');
};

And here's the main script that creates and communicates with it. Try running it!

// This script would run in an HTML page.
// It assumes a 'worker.js' file exists in the same directory.

console.log("Main thread: Starting Web Worker demo.");

try {
  // Create a new Web Worker
  const myWorker = new Worker('worker.js');

  // Listen for messages from the worker
  myWorker.onmessage = function(event) {
    console.log("Main thread: Received result from worker:", event.data);
    console.log("Main thread: UI remains responsive.");
  };

  // Handle errors from the worker
  myWorker.onerror = function(error) {
    console.error("Main thread: Worker error:", error);
  };

  // Send a message to the worker to start a heavy calculation
  const calculationLimit = 200000000; // A large number
  console.log(`Main thread: Sending calculation request for ${calculationLimit} to worker.`);
  myWorker.postMessage(calculationLimit);

  // Demonstrate that the main thread is not blocked
  let count = 0;
  const intervalId = setInterval(() => {
    console.log(`Main thread: UI is active... ${count++}`);
    if (count > 5) { // Stop after a few messages to keep output short
      clearInterval(intervalId);
    }
  }, 100); // This would represent UI updates

} catch (e) {
  console.error("Main thread: Could not create Web Worker. " +
                "This environment might not support Web Workers directly or 'worker.js' is missing.", e);
  console.log("Main thread: Simulating blocking calculation instead.");
  // Fallback for environments without Web Worker support (for CoddyKit's sandbox)
  let sum = 0;
  const limit = 200000000;
  for (let i = 0; i < limit; i++) {
    sum += i;
  }
  console.log("Main thread: Blocking calculation finished. Result:", sum);
  console.log("Main thread: UI would have frozen during this calculation.");
}

Worker Limitations

While powerful, Web Workers have some limitations due to their isolated nature:

  • No DOM Access: Workers cannot directly access or manipulate the Document Object Model (DOM).
  • No Window Object: They cannot access the window, document, or parent objects.
  • Local Files: They cannot access local files directly (e.g., file:// protocol) in all browsers.
  • Communication: All communication must happen via message passing (postMessage and onmessage).

Worker Knowledge Check

Let's check your understanding of Web Workers.

Recap: Offloading Tasks

Great job! You've learned how Web Workers can significantly improve your web application's performance and responsiveness.

  • Web Workers run scripts in the background, off the main thread.
  • They prevent the UI from freezing during heavy computations.
  • Communication occurs through message passing (postMessage and onmessage).
  • Workers cannot directly access the DOM or window object.

By effectively using Web Workers, you can create smoother, more engaging user experiences.

자주 묻는 질문

“웹 워커와 메인 스레드 분리” 강의는 무료인가요?

네 — “웹 워커와 메인 스레드 분리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web Performance Optimization & Lighthouse 강의 전체를 잠금 해제할 수 있습니다. Web Performance Optimization & Lighthouse 강의에는 총 4개의 강의가 포함되어 있습니다.

“웹 워커와 메인 스레드 분리”에서 뭘 배우나요?

계산량이 많은 작업을 웹 워커로 넘겨 메인 스레드를 여유롭게 유지하고 반응성을 확보하는 방법을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Web Performance Optimization & Lighthouse을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Web Performance Optimization & Lighthouse을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Web Performance Optimization & Lighthouse은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“웹 워커와 메인 스레드 분리” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Web Performance Optimization & Lighthouse 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Web Performance Optimization & Lighthouse 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. JavaScript 페이로드 최소화
  2. 효율적인 스크립트 로딩 전략
  3. 웹 워커와 메인 스레드 분리
  4. 코드 분할과 지연 로딩
← Web Performance Optimization & Lighthouse(으)로 돌아가기