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>
?
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"));
});
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.