JavaScript
Image Lazy Loading
Implement image lazy loading with IntersectionObserver.
By EZ4Code Team
imagelazy-loadIntersectionObserver
Code
function lazyLoad(selector = "img[data-src]") {
const observer = new IntersectionObserver((entries, obs) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.removeAttribute("data-src");
obs.unobserve(img);
}
});
});
document.querySelectorAll(selector).forEach(img => observer.observe(img));
}Explanation
Monitors elements entering the viewport via IntersectionObserver for on-demand loading.
More JavaScript Snippets
Array Map Filter Reduce
Chain map, filter, reduce, find, some, and every on arrays.
Array Deduplication
Deduplicate an array using Set.
Deep Clone
Deep clone objects, supporting common data types.
Debounce Function
Wait a period of time after an event triggers before executing; reset the timer if triggered again during the wait.
Throttle Function
Limit a function to execute at most once within a time interval.
Promise.all Concurrency Control
A Promise executor with concurrency limit.