My images are loading very slow on my page so I want to add lazy loading to the images, I have organized them like this, I tried to add img.setAttribute("loading", "lazy"); inside the function createImageNode(bilde) but it didn't do anything
My Js file:
const images = [
{ fil: "Bff tanquery ikke redigert-11.jpg", class: "img-3"},
{ fil: "Bff tanquery-2.jpg", class: "img-3"},
{ fil: "Bff tanquery-3.jpg", class: "img-3"},
{ fil: "Bff tanquery-9.jpg", class: "img-2"},
{ fil: "Bff tanquery.jpg", class: "img-2"},
];
function createImageNode(bilde) {
const div1 = document.createElement("div");
const div2 = document.createElement("div");
const img = new Image();
img.src = `img/${bilde.fil}`;
img.setAttribute("loading", "lazy");
div1.appendChild(div2);
div1.classList.add(bilde.class);
div2.appendChild(img);
div2.classList.add('m2');
return div1;
}
function addImages() {
const arrayImagesElement = document.getElementById("arrayImages");
images.forEach((img) => {
arrayImagesElement.appendChild(createImageNode(img));
});
}
This is what I have in html file to get the images on the page.
<script type="text/javascript">
addImages();
</script>