This is not a duplicate of this because it also uses the document.ready
approach which obviously does not work.
I want to avoid that the browser loads images (<img>
) nested within hidden <div>
elements.
So I tried this, however the javascript gets executed too late, the browser already starts to download images that it shouldn't.
$(document).ready(function() {
$('div').not(":visible").each(function () {
$(this).find('img').each(function() {
$(this).attr("src","");
});
});
});
Is there a good javascript solution for this?
Or do I have to use <img srctmp="...."/>
and then replace srctmp
by src
via javascript for those images which are NOT nested within a hidden <div>
?
Display none don't improve the performance because the goal of virtual scrolling is reduce the number of the elements into the dom. Make an element display none or remove an element, trigger a reflow, but with display none you worst the performance because you don't have the benefit of reduce the dom.
Lazy Loading Images is a set of techniques in web and application development that defer the loading of images on a page to a later point in time - when those images are actually needed, instead of loading them up front.
Images or wrapper elements that have display: none set, will still get loaded. So if you want to eg. load a different image for desktop and mobile, you can either: use display: none , but with the loading="lazy" parameter set on img .
Background images don't get loaded if the element is hidden.
You can use a data
attribute instead the src
, browser loads images only form src
, so you can start with data-src
for every images and then add the src
only to the visible ones.
HTML:
<img data-src="path/to/image.jpg" />
JS:
$(document).ready(function() {
$('div').is(":visible").each(function () {
$(this).find('img').each(function() {
$(this).attr("src", $(this).data("src"));
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With