Resolved

D3.js force simulation freezes page load animations

D3.js
JavaScript
Frontend
Performance
Canvas
Astro
UI/UX
Optimization

Heavy D3.js canvas initialization blocks main thread during page load | Causes background animations to freeze until simulation completes

A D3.js force-directed graph in an Astro frontend was causing page load animations to freeze due to heavy canvas initialization. The issue occurred even though the visualization was hidden, blocking the main thread and creating a poor user experience.

Issue

The page load animations froze for 1-3 seconds because the D3.js force simulation and canvas rendering were initialized automatically, even when hidden behind a button. This blocked the main thread, preventing background animations from running smoothly.

Culprit

The issues were caused by:

  • Automatic Initialization: The D3.js canvas initialized automatically during page load, regardless of visibility.
  • Unoptimized Force Simulation: Default D3.js simulation parameters led to prolonged CPU usage, blocking the main thread.

Solution

On-Demand Loading Pattern

The initialization of the D3.js canvas was modified to be triggered only by user interaction, rather than automatically during page load. This eliminated the freeze during the initial load phase.

Force Simulation Optimization

The force simulation parameters were optimized to reduce settling time and CPU usage, including:

  • Increasing the alpha decay rate to achieve faster settling.
  • Setting a higher alpha minimum threshold to stop the simulation earlier.
  • Adjusting the velocity decay to dampen the simulation more quickly.

Outcome

The page load no longer freezes, allowing background animations to run smoothly. The D3.js simulation now runs only when explicitly triggered by the user, improving performance and user experience.