Client:load vs client:idle vs client:visible in Astro: Key Differences
client:load hydrates a component immediately after the page loads, client:idle waits until the browser is idle to hydrate, and client:visible hydrates only when the component scrolls into the viewport. These directives help optimize when JavaScript runs for better performance.Quick Comparison
Here is a quick side-by-side comparison of the three hydration directives in Astro:
| Feature | client:load | client:idle | client:visible |
|---|---|---|---|
| When hydration starts | Right after page load | When browser is idle | When component enters viewport |
| Performance impact | Higher initial load cost | Lower initial load cost | Lowest initial load cost |
| Use case | Critical interactive UI | Non-urgent UI | UI below the fold or offscreen |
| Browser support | All modern browsers | All modern browsers | All modern browsers with IntersectionObserver |
| JavaScript execution timing | Soon after DOM ready | Delayed until idle | Triggered by visibility event |
Key Differences
client:load hydrates the component as soon as the page finishes loading. This means the JavaScript runs immediately after the HTML is parsed, making the component interactive quickly but increasing the initial load time.
client:idle waits for the browser to become idle before hydrating. It uses the browser's requestIdleCallback API to delay JavaScript execution until the main thread is free, improving page load performance by deferring non-critical scripts.
client:visible delays hydration until the component scrolls into the user's viewport. It uses the Intersection Observer API to detect visibility, so JavaScript runs only when the user is likely to interact with the component, saving resources on components offscreen.
Code Comparison
Example of using client:load to hydrate a simple counter component immediately after page load:
<script> import Counter from '../components/Counter.jsx'; </script> <Counter client:load />
client:idle Equivalent
Using client:idle to hydrate the same counter component only when the browser is idle:
<script> import Counter from '../components/Counter.jsx'; </script> <Counter client:idle />
When to Use Which
Choose client:load when your component needs to be interactive immediately, such as navigation menus or critical UI elements.
Choose client:idle for components that enhance the page but are not urgent, like analytics widgets or secondary features.
Choose client:visible for components that appear below the fold or offscreen, such as image galleries or ads, to save resources until the user scrolls to them.
Key Takeaways
client:load hydrates immediately after page load for fast interactivity.client:idle delays hydration until the browser is idle to improve load performance.client:visible hydrates only when the component enters the viewport, saving resources.