# Lazy loading
- To lazy load images use the data-src attribute as default attribute for loading image locations.
ex -> data-src="images/Extracted_HeroImage_sd.png"
### code for lazy loading
var images = document.querySelectorAll("[data-src]");
function preloadImage(img) {
var src = img.getAttribute("data-src");
console.log(src);
if (!src) {
return;
}
img.src = src;
}
var imgOptions = {
threshold: 0,
rootMargin: "0px 0px 200px 0px"
};
var imgObserver = new IntersectionObserver((entries, imgObserver) => {
entries.forEach(entry => {
if (!entry.isIntersecting) {
return;
} else {
preloadImage(entry.target);
imgObserver.unobserve(entry.target);
}
})
}, imgOptions);
images.forEach(image => {
imgObserver.observe(image);
})
// lazy loading images End.
## intersection observer
The default js method intersection observer has been used for observing if the use is anywhere near the image. the default value has been set to 200px which means that if the user comes 200px near the image the observer is triggere and the image is viewed.
var imgOptions = {
threshold: 0,
rootMargin: "0px 0px 200px 0px"
};
we can change that value simply by changing the rootMargin value.
## Swapping images from low to high resolution
- It is importatnt that data-src attribute is used as the default attribute to provide image location
ex < img data-src="images/Extracted_HeroImage_sd.png" class="slider-image oimage"/>
- oimage class must be used
ex < img data-src="images/Extracted_HeroImage_sd.png" class="slider-image oimage"/>
- The defalut image must be of low resolution with the _sd after the name of the image which will later be switched with the higher resolution image example from the point above.
- The lower resolution images will need ot have the same extension as the higher resolution images
ex < img data-src="images/Extracted_HeroImage_sd.png" class="slider-image oimage"/>(low - resolution)
ex < img data-src="images/Extracted_HeroImage.png" class="slider-image oimage"/>(high- resolution.
## Backed working of image swapping
$(".oimage").each(function (index) {
var value = $(this).data("src");
var file_Extension_Return = value.slice((value.lastIndexOf(".") - 1 >>> 0) + 2);
var imgDisplay = value.split('.').slice(0, -1).join('.');
var finalDisplay = imgDisplay.split("_sd");
$(this).attr('data-src', finalDisplay[0] + "." + file_Extension_Return);
})
in the code above we are grabbing all the imagees with the class of oimage and extracting the value from data src attribute line 1,2. Then we are saving the image file extension ndn removing the file extension inline 3,4 then finally we are removing the _sd from the file name and switching the image location in line 5,6.
### Precautions
- use data-src as default attribute to lazy load images and optimize images.
- _sd must be used after the name of the image for low resulotion images.
- both low and high resolution images must be saved in t same direcotry.
[README.md](:/9ae8d10297f742b88816b0462c072768)