User Agents

Web browsers and everyday web tech, explained

Why Safari May Run a Module Workers Entry File Twice

· 5 min read · Browsers

In this article
  1. Background: How Module Workers Differ from Classic Workers
  2. Why Does Safari Run It Twice? The Core Reasons
  3. How to Detect If It’s Happening
  4. Common Misconceptions: It’s Not a Bug in Your Code
  5. How to Prevent Double Execution
  6. When Does It Actually Matter?
  7. Frequently Asked Questions

Safari may run a module worker's entry file twice because of a combination of how Safari handles module scripts and a known quirk in its worker lifecycle: the browser can instantiate the worker module graph more than once during a single page load, particularly when the worker is created before the page's main script has fully parsed or when the worker script is fetched as part of a preload scan. This is not a bug in your code, but rather a consequence of Safari's speculative loading and its implementation of the module worker specification. Below, we break down the exact reasons, when it happens, and how to avoid it.

Background: How Module Workers Differ from Classic Workers

Web Workers are background scripts that run on a separate thread. Classic workers load a single JavaScript file and execute it top-to-bottom. Module workers, introduced later, use the import and export syntax, allowing you to split code into multiple files. The key difference is that module workers have a dependency graph: the browser must fetch and evaluate the entry file and all its imports before the worker starts running.

Safari's handling of module workers has historically been less mature than Chrome or Firefox. In particular, Safari's JavaScript engine (JavaScriptCore) and its HTML parser interact in ways that can cause the entry file to be evaluated twice. This is not a deliberate feature, but a side effect of how Safari schedules worker initialization relative to the main thread's parsing.

Why Does Safari Run It Twice? The Core Reasons

There are three main scenarios that trigger a double execution:

  • Speculative preload: Safari's parser may preload the module worker script as soon as it sees the new Worker() call, even before the main script has finished executing. If the worker is created again later (e.g., because the page re-runs the same code), the entry file is fetched and executed again.
  • Module graph re-evaluation: In some Safari versions, if a module worker is created while the main thread is still parsing, the worker's module graph is evaluated once during the preload and again when the worker actually starts. This is similar to a race condition in the browser's internal scheduling.
  • Page lifecycle events: Safari may re-create a worker when the page goes through certain lifecycle transitions (e.g., bfcache restore, or when the page is moved to a different process). Each creation triggers a fresh evaluation of the entry file.

In practice, the most common trigger is the preload scan. Safari's HTML parser scans the document for resource hints, and new Worker() is treated as a resource hint. If the worker is created in a module script that is deferred or async, the preload can happen before the main script executes, and then the actual worker creation happens again when the script runs.

How to Detect If It’s Happening

You can confirm a double execution by adding a log statement at the top of your worker entry file:

console.log('worker started at', Date.now());

If you see two log entries with different timestamps (or even the same timestamp) in the browser console, the file ran twice. However, note that in some cases the second execution may be from a different worker instance (e.g., if you create multiple workers). To isolate, add a unique ID to each worker creation and log it.

Another way is to use the Performance API: performance.getEntriesByType('resource') will show two entries for the same worker script URL if it was fetched twice.

Common Misconceptions: It’s Not a Bug in Your Code

Many developers assume they made a mistake—perhaps they called new Worker() twice, or they have a side effect in the module top-level that runs on import. While those are possible, Safari's double execution can happen even with a single worker creation and a pure module with no side effects. The reason is that the module graph is evaluated once for the preload and once for the actual worker start. This is a known Safari behavior, and it has been reported in WebKit bug trackers. It is not something you can fix by changing your code's logic; you need to work around it.

How to Prevent Double Execution

There are several strategies to avoid the double run:

  1. Use a guard flag: At the top of your entry file, check a global flag (e.g., self.__workerStarted) and skip initialization if it's already set. This is the simplest and most reliable workaround.
  2. Defer worker creation: Create the worker after the page's DOMContentLoaded event, or use setTimeout(0) to ensure the main script has fully parsed. This reduces the chance of preload racing.
  3. Use a classic worker if you don't need modules: Classic workers do not exhibit this issue because they are not preloaded as module graphs.
  4. Update Safari: Apple has fixed some related bugs in recent versions, so keeping Safari up to date may resolve the issue.

For example, a guard flag looks like this:

if (self.__workerStarted) { return; } self.__workerStarted = true; // rest of your code

Note that return at the top level of a module is allowed, so this works.

When Does It Actually Matter?

Double execution only matters if your worker has side effects at the top level, such as starting timers, making network requests, or initializing a database. If your worker only defines functions and waits for messages, the second run is harmless (though it wastes resources). In most real-world workers, you do have initialization code, so it's worth guarding.

Also, note that the double execution can cause subtle bugs: for instance, if you set up an event listener in the worker, you might end up with two listeners, leading to duplicate message processing. Guarding against it prevents these issues.

Frequently Asked Questions

Does this happen in Chrome or Firefox?

No, this specific double-execution behavior is unique to Safari (and occasionally older WebKit-based browsers). Chrome and Firefox handle module worker preloading differently and do not evaluate the entry file twice in normal circumstances.

Can I avoid using module workers entirely?

Yes, you can use classic workers, but you lose the ability to use import/export. If your worker code is small, a classic worker is a simple workaround. If you need modules, use the guard flag.

Will this be fixed in future Safari versions?

Apple has acknowledged similar issues and has made improvements, but as of now, there is no guarantee that all double-execution scenarios are fixed. The guard flag is the safest approach for production.

Is there a performance impact?

Yes, the double execution means the worker script is fetched and evaluated twice, which can increase load time and memory usage. For large modules, this can be noticeable.

Does this affect service workers?

Service workers have a different lifecycle and do not exhibit this double-execution issue. The problem is specific to dedicated workers created via new Worker().