# Lazy loading and infinite scroll — Web Performance Optimization

Source: https://www.skillbyai.com/en/web-performance/web-perf-10

> Load resources and content on-demand as users interact, reducing initial payload and improving perceived performance.

## Intersection Observer API

Detect when elements enter viewport: `new IntersectionObserver((entries) => { entries.forEach(e => e.isIntersecting && loadImage(e.target)); })`. No scroll listeners needed. More efficient than scroll events.

## Lazy loading strategies

Native `loading="lazy"` for images, dynamic imports for JavaScript, `<link rel=preload>` for critical resources. Use placeholders (blur-up, skeleton screens) to maintain layout and reduce CLS.

## Lazy loading performance gains

Typically reduces initial payload by 30-50% on long pages. Improves LCP and FCP. However, can worsen scroll performance if not implemented carefully. Test on real devices.

Quick check

**Quiz:** What is Intersection Observer used for?

- [ ] Measuring page load time
- [ ] Compressing images
- [x] Detecting when elements enter viewport
- [ ] Encrypting network requests

*Answer:* Detecting when elements enter viewport. It reports when elements cross the viewport without costly scroll listeners.
