Do not upload images to hidden elements

This is not a duplicate of this , because it also uses the document.ready approach, which obviously does not work.

I want the browser not to load images ( <img> ) nested in hidden <div> elements.

So, I tried this, however javascript starts too late, the browser is already starting to load images that it should not.

  $(document).ready(function() { $('div').not(":visible").each(function () { $(this).find('img').each(function() { $(this).attr("src",""); }); }); }); 

Is there a good solution for this? Or do I need to use <img srctmp="...."/> and then replace srctmp with src via javascript for those images that are NOT nested in a hidden <div> ?

+5
source share
1 answer

Instead of src you can use the data attribute, the browser only downloads src forms, so you can start with data-src for each image, and then add src only to 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")); }); }); }); 
+4
source

All Articles