Back to Playground
Performance

Intersection Observer API

Lazy loading images and triggering animations on scroll using the Intersection Observer API.

JavaScriptWeb APIsReact

Intersection Observer API

Scroll down to see images load lazily and animations trigger as elements enter the viewport. This technique improves performance by only loading content when needed.

💡 Tip: Open DevTools Network tab to see images loading as you scroll!

Lazy Loading Images

Waiting to load...

Image 1

Waiting to load...

Image 2

Waiting to load...

Image 3

Waiting to load...

Image 4

Waiting to load...

Image 5

Waiting to load...

Image 6

Scroll-Triggered Animations

These sections animate in as you scroll. They also animate out when you scroll back up!

Performance Optimization

Hidden

Only load images when they enter the viewport, saving bandwidth and improving initial page load time.

Smooth Animations

Hidden

Trigger animations as elements come into view for a more engaging user experience.

Lazy Loading

Hidden

Defer loading of off-screen content until the user scrolls near it.

Infinite Scroll

Hidden

Detect when users reach the bottom of the page to load more content automatically.

Benefits

50%

Faster Initial Load

70%

Less Bandwidth Used

100%

Better UX

Code

const LazyImage = ({ src, alt }) => {
  const [isVisible, setIsVisible] = useState(false)
  const imgRef = useRef(null)
  
  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true)
          observer.disconnect()
        }
      },
      { threshold: 0.1 }
    )
    
    if (imgRef.current) {
      observer.observe(imgRef.current)
    }
    
    return () => observer.disconnect()
  }, [])
  
  return (
    <img
      ref={imgRef}
      src={isVisible ? src : ''}
      alt={alt}
    />
  )
}