Lazy Load Images
JavaScript
Medium
4 views
Problem Description
Images have data-src and class lazy. When an image is near viewport, set its src from data-src and remove class lazy. Use IntersectionObserver.
Output Format
No output (DOM change).
Constraints
Assume images .lazy exist and browser supports IntersectionObserver.
Official Solution
const imgs=[...document.querySelectorAll('img.lazy[data-src]')];const io=new IntersectionObserver(entries=>{for(const en of entries){if(!en.isIntersecting)continue;const img=en.target;img.src=img.dataset.src||'';img.classList.remove('lazy');io.unobserve(img);}}, {root:null,rootMargin:'200px',threshold:0.01});for(const img of imgs)io.observe(img);
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!