0
0
AstroConceptBeginner · 3 min read

What is client:visible in Astro: Explanation and Usage

client:visible in Astro is a directive that loads and runs a component only when it becomes visible in the browser viewport. It helps improve page speed by delaying JavaScript until the user scrolls to the component.
⚙️

How It Works

Imagine you have a webpage with many parts, but you only want to load some interactive pieces when the user actually sees them. client:visible works like a smart helper that waits until the component scrolls into view before turning it on.

This means the component's JavaScript is not loaded or run right away. Instead, the browser watches the page, and when the component appears on the screen, Astro loads and activates it. This saves time and resources, making the page faster and smoother.

Think of it like a streetlight that only turns on when someone walks under it, instead of lighting the whole street all night.

💻

Example

This example shows a simple Astro component that uses client:visible to load a button only when it scrolls into view.

astro
---
import Counter from '../components/Counter.jsx';
---

<section style="height: 150vh;">
  <p>Scroll down to see the counter load.</p>
</section>

<Counter client:visible />
Output
<section style="height: 150vh;"><p>Scroll down to see the counter load.</p></section><button>Count: 0</button>
🎯

When to Use

Use client:visible when you want to improve page load speed by delaying JavaScript for components that are not immediately visible. This is great for:

  • Long pages with interactive widgets far down the page.
  • Images or maps that only need interaction when seen.
  • Third-party widgets that slow down initial load.

It helps users get content faster and reduces unnecessary work for the browser.

Key Points

  • client:visible delays loading until the component is visible in the viewport.
  • It improves performance by reducing initial JavaScript load.
  • Works well for components below the fold or rarely seen.
  • Uses browser Intersection Observer under the hood.
  • Easy to add by placing client:visible on the component tag.

Key Takeaways

client:visible loads components only when they appear on screen to save resources.
It improves page speed by delaying JavaScript for off-screen components.
Ideal for long pages or rarely used interactive parts.
Implemented easily by adding client:visible to component tags.
Uses browser features to detect visibility without extra code.