6

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>?

6
  • 1
    I believe setting the src attribute to "" doesnt impact this. Try to remove the attribute whole after saving it to data-src or something? Commented Jul 23, 2015 at 15:15
  • 1
    It’s impossible to stop image sources from being downloaded via JavaScript. You’ll have to leave the src attribute empty and then insert it later it with another attribute, but use data-srctmp instead. Commented Jul 23, 2015 at 15:15
  • The code inside $(document).ready(function() {...}); will always get executed after the DOM is ready (meaning after all the images and content has been loaded). So don't use ready. Commented Jul 23, 2015 at 15:17
  • possible duplicate of Prevent images from loading Commented Jul 23, 2015 at 15:18
  • @AbraarArique But without ready you can’t access any element. When images finish loading the load event is dispatched, not DOMContentLoaded (ready). Commented Jul 23, 2015 at 15:19

1 Answer 1

5

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")); }); }); }); 
Sign up to request clarification or add additional context in comments.

1 Comment

This looks very promising. I will try it out and select it as solution if it works. Thanks for your time.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.