In a comment by @bo-wahlstrøm, the most effective strategy is outlined. The concept of lazy loading can be considered a hack that has versatile applications! This means it can be implemented on various elements, such as image tags or JavaScript scripts. Browsers are designed to automatically fetch resources when there are changes in certain attributes.
The approach involves initially loading an empty <img src="">
tag but adding a data attribute that doesn't trigger automatic fetching: <img src="" data-src="myimage.jpg">
.
By using the Intersection Observer, we can set the src attribute once the user reaches a specific distance from the observer box (e.g., 100px from the bottom). This transforms <img src="" data-src="myimage.jpg">
into <img src="myimage.jpg" data-src="myimage.jpg">
.
This method can also be applied to script src attributes and even CSS url properties for similar results.
That's all there is to it!