Html
<img
width="1024"
src="https://placehold.it/64x48.jpg"
data-src-defer="https://images.unsplash.com/photo-1570280406792-bf58b7c59247?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1486&q=80"
alt="image 1"
/>
<img
width="1024"
src="https://placehold.it/64x48.jpg"
data-src-defer="https://images.unsplash.com/photo-1557053964-d42e8e29cb27?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1500&q=80"
alt="image 2"
/>
JS
function deferImgs() {
Array
.from(document.querySelectorAll("img[data-src-defer]"))
.forEach((element) => {
element.setAttribute("src", element.dataset.srcDefer);
});
}
window.addEventListener("load", deferImgs());
================================================================
I'm trying to comply with Farrukh's request with this edit.
I try to do my best, but English is unfortunately only the third language I speak. And I am not a language genius. :D
This js code snippet illustrates a delayed load of some big pictures.
This is not a practical implementation.
The size difference between the images is intentionally huge.
This is because the test must be illustrative.
You can monitor its operation through a browser development tool page.
F12 > Network tab > Speed settings dropdown
The ideal network speed for the test is between 1 - 3MB/s (Some slow network speed).
You may want to run the test several times, so you can see, that the order in which the images are loaded is not controlled in this case, but depends on the transmission.
Because it is not regulated, it is not possible to predict, which image will arrive first.
We load first a small image into a large placeholder.
(image: 64x48.jpg > placeholder width="1024").
The querySelectorAll() method returns a static nodelist. This list of nodes at first glance looks like an array, but it's not.
This is an array-like object:
document.querySelectorAll("img[data-src-defer]")
The Array.from() method can creates a new array instance from this object.
The forEach method can now be executed on this array.
The forEach() method executes a provided function once for each element of the array.
In this case, each element of the array is passed once to this function:
(element) => {
element.setAttribute("src", element.dataset.srcDefer);
}
and this function sets the value of the src="" attribute of the image tag, to the value of the dataset of the same image tag.
src="https://placehold.it/64x48.jpg";
data-src-defer="https://images.unsplash.com/photo-1570280406792-bf58b7c59247?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1486&q=80";
src = data-src-defer;
So finally:
src="https://images.unsplash.com/photo-1570280406792-bf58b7c59247?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1486&q=80";