0
0
Astroframework~30 mins

client:visible for viewport-based loading in Astro - Mini Project: Build & Apply

Choose your learning style9 modes available
Lazy Load Images with Astro's client:visible
📖 Scenario: You are building a simple webpage that shows a list of images. To improve performance, you want each image to load only when it scrolls into the user's view.
🎯 Goal: Create an Astro component that uses client:visible to lazy load images as they appear in the viewport.
📋 What You'll Learn
Create an array of image URLs in Astro frontmatter
Add a variable to hold the image width for consistent sizing
Use client:visible on the image component to load images only when visible
Complete the Astro component with proper HTML structure and accessibility
💡 Why This Matters
🌍 Real World
Lazy loading images improves website speed and user experience by loading images only when needed, saving bandwidth and reducing initial load time.
💼 Career
Understanding client directives like client:visible in Astro is important for frontend developers to optimize performance and build modern, efficient web applications.
Progress0 / 4 steps
1
Set up the image URLs array
In the frontmatter of your Astro component, create a constant called imageUrls that is an array containing these exact strings: "/images/photo1.jpg", "/images/photo2.jpg", "/images/photo3.jpg".
Astro
Hint

Use square brackets to create an array and include the exact image paths as strings.

2
Add image width configuration
Below the imageUrls array, create a constant called imageWidth and set it to 300 to define the width for all images.
Astro
Hint

Just add a new constant with the exact name and value.

3
Use client:visible to lazy load images
In the component's HTML, use a {imageUrls.map((url) => ( ... ))} expression to loop over imageUrls. Inside the loop, create an <img> tag with src={url}, width={imageWidth}, alt="Photo", and add the attribute client:visible to enable lazy loading when the image enters the viewport.
Astro
Hint

Use curly braces to embed JavaScript expressions in Astro HTML and add client:visible as an attribute on the <img> tag.

4
Complete the Astro component with semantic HTML
Wrap the images inside a <main> tag and add an <h1> heading with the text "Lazy Loaded Gallery" above the images for accessibility and structure.
Astro
Hint

Use semantic tags for better accessibility and structure.