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.