Course contentsShow
← JavaScript
Lesson 2148 of 2,72345. Workers and ConcurrencyFree lesson

Creating a Web Worker

Understand how to instantiate a Web Worker using the Worker constructor and specify the script file to execute.

Creating a Web Worker

You'll learn how to instantiate a Web Worker from a separate script file and start running code off the main thread.

Now that you know what Web Workers are—a way to run JavaScript in parallel on a separate thread—it's time to create one. The process is straightforward: you use the Worker constructor and point it to a JavaScript file that contains the code you want to run in the background.

The Worker Constructor

To create a Web Worker, instantiate the Worker class and pass the path to your worker script:

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

This single line:

  • Creates a new background thread
  • Loads and executes the script file worker.js in that thread
  • Returns a Worker object you can use to communicate with it

The path can be relative to your HTML file or an absolute URL. The browser handles downloading and running the script in isolation from your main thread.

The Worker Script File

The file you reference (worker.js in the example above) is a separate JavaScript file. It doesn't have access to the DOM, window, or most browser APIs available on the main thread. It runs independently.

Think of it like hiring a specialist: you give them their own workspace (the script file) and their own instructions. They work separately from your main office (main thread) but can send messages back and forth.

When the Worker Starts

The moment you call new Worker(), the browser begins loading and executing the script. There's no separate "start" method—creation and execution happen together.

Key Takeaway:
Create a Web Worker with new Worker('script.js'), passing the path to a separate JavaScript file that will execute on its own thread.