Sign inSign up

Native JavaScript Image Lazy Loading Plugin

Add-ons
2026-07-26 00:59 4 views • 0 downloads 2.7KB
Native JavaScript Image Lazy Loading Plugin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Get all img elements with data-src attributes
var limg = document.querySelectorAll("img[data-src]")
// Array.prototype.forEach.call() is a quick way to access forEach and replace the empty array as this with the list you want to iterate over.
Array.prototype.forEach.call(limg, function(item, index) {
var rect
// Skip if data-src is empty
if (item.getAttribute("data-src") === "")
return
// getBoundingClientRect is used to obtain an element's position relative to the viewport. The returned object contains properties such as top, right, bottom, and left.
rect = item.getBoundingClientRect()
// Dynamically load images when they enter the visible area
if (rect.bottom >= 0 && rect.top < viewHeight) {
(function() {
var img = new Image()
img.src = item.getAttribute("data-src")
item.src = img.src
// Add a transition effect to the image to make it appear smoothly
var j = 0
setInterval(function() {
j += 0.2
if (j <= 1) {
item.style.opacity = j
return
}
}, 100)
// Remove data-src
item.removeAttribute('data-src')
})()
}
})