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

Importing Scripts in Workers

Understand how to load external JavaScript files inside a worker using the importScripts() function for code reuse.

Importing Scripts in Workers

You'll learn how to load external JavaScript files inside a Web Worker using importScripts() to organize and reuse code across your worker environments.


Why Import Scripts in Workers?

Workers run in an isolated environment without access to the DOM or the main thread's global scope. This means you can't use <script> tags or standard module imports (in classic workers). Instead, workers provide importScripts(), a synchronous function that fetches and executes one or more external JavaScript files directly into the worker's global scope.

Think of importScripts() like copying entire JavaScript files directly into your worker at runtime—everything declared in those files becomes available immediately.


How It Works

Inside your worker file, call importScripts() with one or more URLs:

// worker.js
importScripts('utils.js', 'calculations.js');

// Now you can use functions from those files
const result = calculateSomething(data);
postMessage(result);

The imported scripts execute in order, synchronously, before any subsequent code runs. This makes code organization cleaner—you can extract shared utilities, libraries, or constants into separate files.


Key Considerations

  • Synchronous loading: Unlike module imports, importScripts() blocks execution until all scripts load
  • Same-origin policy applies: Scripts must be from the same origin or served with proper CORS headers
  • Global scope pollution: All imported variables/functions become global within the worker
  • Only for classic workers: Module workers use standard import syntax instead

Key Takeaway:
Use importScripts() in classic workers to synchronously load external JavaScript files, enabling code reuse and better organization without polluting the main thread's scope.