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

Community
  • 1
  • 1
basZero
  • 3,868
  • 8
  • 45
  • 84
  • 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? – Alex Jul 23 '15 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. – Sebastian Simon Jul 23 '15 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`. – Abraar Arique Diganto Jul 23 '15 at 15:17
  • possible duplicate of [Prevent images from loading](http://stackoverflow.com/questions/1667868/prevent-images-from-loading) – Sebastian Simon Jul 23 '15 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`). – Sebastian Simon Jul 23 '15 at 15:19
  • How else do you want to access your `` elements before loading, if not with `document.ready`? This is impossible; therefore the duplicate flag is still valid (even solely for the reason that the answers will be identical). – Sebastian Simon Jul 23 '15 at 15:31

1 Answers1

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"));
       });
    });
  });
michelem
  • 13,169
  • 4
  • 44
  • 60
  • This looks very promising. I will try it out and select it as solution if it works. Thanks for your time. – basZero Jul 23 '15 at 18:29