92Build a lazy image loader using IntersectionObserver
mediumAbout 35 minutesCodingintersection-observerimagesperformancedom
Problem
Without a framework, implement lazyLoadImages(root = document, { rootMargin = "200px", loadedClass = "loaded" } = {}). Images are written as:
<img data-src="/photos/1.jpg" data-srcset="/photos/1.jpg 1x, /photos/1@2x.jpg 2x" alt="…" width="600" height="400">- Observe every
img[data-src]insiderootwith oneIntersectionObserver(usingrootMarginso images start loading just before they scroll into view). - When an image intersects, copy
data-srcsettosrcsetanddata-srctosrc, remove thedata-*attributes, and stop observing it. - When the image's
loadevent fires, addloadedClass(for a fade-in). - If
IntersectionObserveris not available, load every image immediately. - Return
{ observe(img), disconnect() }, so images added later (for example by infinite scroll) can be registered.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
App.jsxReact + DOM
Step-by-step
load(img): attach a load listener that adds the class, then set srcset before src (so the browser picks the right candidate on the first request), and remove data-src and data-srcset.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 4 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.