Lazy Loading
Make apps blazing fast. Master Intersection Observer for lazy images, dynamic import() for code splitting, route-based lazy loading, prefetching strategies, and measuring LCP improvements.
What You Will Build
Lazy Images
IntersectionObserver swaps data-src to src just before the image scrolls into view
Dynamic import()
Load JavaScript modules on demand — not before the user needs them
Route Splitting
Each route gets its own bundle chunk — ship only what the current page needs
Prefetching
Load the next page silently during idle time so navigation feels instant
Lazy Loading Techniques
| Technique | When to use | Key API | Gotcha |
|---|---|---|---|
| Lazy images (native) | Images below the fold | loading="lazy" | No control over threshold |
| Lazy images (Observer) | Fine-grained control | IntersectionObserver | Must unobserve after load |
| Dynamic import() | Heavy libraries, rare features | import('./mod.js') | Bundler must see static string for splitting |
| Route splitting | SPA with many pages | React.lazy / import() | Need Suspense/fallback for UX |
| Prefetch on hover | Predictive — fast navigation | requestIdleCallback + import() | Don't prefetch on slow networks |
| <link rel=prefetch> | Entire pages/assets | HTML hint | May be ignored by browser |
| fetchpriority hint | Boost or demote LCP image | fetchpriority="high" | Only affects fetch priority, not laziness |
Common Pitfalls
Build It Live
Code Editor
<p>Scroll inside the preview: images and the "heavy" widget load only when they come into view.</p>
<div class="spacer">↓</div>
<img data-src="https://picsum.photos/id/1015/400/200" alt="River" width="400" height="200">
<div class="spacer">↓</div>
<img data-src="https://picsum.photos/id/1016/400/200" alt="Canyon" width="400" height="200">
<div class="spacer">↓</div>
<div id="widget">Widget not loaded yet</div>
<p id="log"></p>Preview
Course Complete! 🎉
Congratulations! You have completed the full JavaScript curriculum — from variables and functions all the way to lazy loading, routing, and real-time apps. You now have the skills to build modern, performant, production-ready JavaScript applications.
Lazy Loading — step by step
IntersectionObserver API
IntersectionObserver fires a callback when a target element enters or exits the viewport. You create an observer with a callback and options (threshold, rootMargin), then call observer.observe on each element you want to watch.
🎯 Quick Check
What should you do after an element finishes lazy loading to avoid unnecessary work?
Final page reached