41

is there a way with javascript/jquery to prevent images from loading? I am building a slideshow from a html list with images. So I would like to collect all the src data and then prevent the images from loading. So later when the user really needs the image I would load it then.

I found some lazy loading script on google but couldn't find the way they prevent images from loading.

Thanks in advance.

Edit1:
It seems from the answers that it's not possible to use javascript to prevent images from loading. Here is a script that does lazy loading. Could anybody explain how it works? It seems when javascript is off it just loads the images normaly and when it's on it will load them when you scroll to their location.

Pickels
  • 33,902
  • 26
  • 118
  • 178
  • I've amended my answer to address your edit. – Langdon Nov 03 '09 at 15:30
  • Thanks, I commented your answer. – Pickels Nov 03 '09 at 15:52
  • Amended again, it seems that removeAttr("src") does the trick, although it's surprising that (a) the JavaScript doesn't execute before the IMG tags are even created, and (b) that the JavaScript would prevent the browser from making requests to the server (maybe requests are still made, but canceled). – Langdon Nov 03 '09 at 16:56
  • Yep, I even tested the removeAttr("src") before asking the question here. But because I tested it locally with small images it didn't work. I guess jquery isn't loaded in time to stop/cancel the images from being loaded. So even in an online senario small images could still get loaded but that's not really a big problem. – Pickels Nov 03 '09 at 17:27
  • Couldn't resist digging deeper... I forgot that $( was shorthand for $(document).ready... and I'm guessing your test of removeAttr("src") didn't execute before after the document was ready, but before the body had loaded. I simplified the solution dramatically in my answer. – Langdon Nov 03 '09 at 17:44

11 Answers11

38

You can wrap the image in a noscript tag:

<noscript>
<img src="foo.jpg"/>
</noscript>

All browsers that has JavaScript enabled will ignore the image tag so the image won't load.

Sheldon
  • 552
  • 6
  • 12
20

If you render the HTML on the page, even if it's hidden, it's going to load. If you want images to load only when they're needed, you're going to have to dynamically set the source (src) on the image tag in javascript.

Edit 1: The script you referenced merely checks to see how far you've scrolled the page down and then determines which images are visible (or almost visible) by checking their top -- see the $.belowthefold and $.rightoffold extensions.

The example works great when the images are all the same size because their containers can also be the same size and you won't get any odd page resizing behavior when you lazy load them. If your images' heights and widths vary, you may get some odd results.  

Edit 2:

<script type="text/javascript" charset="utf-8">
    $(document).ready( function() { $("img").removeAttr("src"); } );
</script>

<img src="Chrysanthemum.jpg" />
<img src="Desert.jpg" />
<img src="Hydrangeas.jpg" />
<img src="Jellyfish.jpg" />
<img src="Koala.jpg" />
<img src="Lighthouse.jpg" />
<img src="Penguins.jpg" />
<img src="Tulips.jpg" />
Aashish Kumar
  • 2,771
  • 3
  • 28
  • 43
Langdon
  • 19,875
  • 18
  • 88
  • 107
  • 1
    But don't they need to prevent loading the images for this script to be useful? If I check with firebug I only see the GET images when I scroll to their location. So there has to be a mechanism to stop them from loading in the first place? – Pickels Nov 03 '09 at 15:37
  • Sorry, I lost site of the original question. It looks like your answer is here: $(self).removeAttr("src"); self.loaded = false; – Langdon Nov 03 '09 at 16:45
  • 2
    $("img").removeAttr("src").css('display':'none'); might be better as some browsers (Firefox) will show broken little icons if there's no SRC attribute for an IMG element. – Wells Nov 03 '09 at 17:50
  • This doesn't work work anymore in latest browsers. eg. chrome 12 :( – ADmad Sep 08 '12 at 14:54
  • @ADmad it's like as a result of Chrome's initiative to load sites faster... see Aaron's answer below and use an attribute other than src="" to temporarily store the src. – Langdon Sep 10 '12 at 13:20
  • 1
    @Langdon yes I am aware of that method. The thing I is was actually trying to write a greasemonkey script to prevent loading of specific images for a particular site. So the method suggested by Aaron won't work for my needs as the generated html is not under my control. Edit: Just to clarify further I am not trying to implement lazy loading. Just wanted to prevent loading of image altogether which i do not want to see for a 3rd party site using greasemonkey script :) – ADmad Sep 11 '12 at 12:42
14

Store the URLs somewhere else, then set all image URLs to some dummy image (empty, transparent, "loading data...", whatever). When an image should be displayed, use JS to set the src attribute and the browser will fetch it.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • This one is good solution for the question. But when you need to do some SEO on your website it's not getting indexed properly without correct image on `src`. – Eranda Jan 27 '16 at 05:21
  • @Eranda Point the indexer bot to a different page which is suitable for robots. – Aaron Digulla Jan 27 '16 at 17:12
4

Well with Prototype you can do something like this I guess:

var unloaded = [];
$$('img.noload').each(function (image) {
    unloaded.push(image);
    image._src = image.src;
    image.src = '';
});

To load all of them:

unloaded.each(function (image) {
    image.src = image._src;
});

To load the first one:

function loadImage (image) {
    image.src = image._src;
}

loadImage(unloaded.shift());

Well I hope you got the idea.

Kaze no Koe
  • 3,254
  • 1
  • 21
  • 22
1

Just do not include the img tag in your original HTML, generate it on the fly using DHTML as you need it. You can also put a fake url to image in the img tag and replace it with the real one dynamically.

On the side note - what's the point. All you are trying to do here is to build another caching mechanism over the existing one. Leave caching to browsers, they are pretty good at this

mfeingold
  • 7,094
  • 4
  • 37
  • 43
  • 2
    The reason why I needed this mechanism is because I am making a slideshow. So if there are 30 images I don't want to load all 30 if the user is only going to view a couple of images. – Pickels Nov 03 '09 at 15:15
1

You can use the portion below to replace all image tags with a dummy file (for example, an 1x1 transparent gif). The url's are stored in a array for later reference.

$(document).ready(function(){
    var images = new Array();
    $("img").each(function(i){
      images[i] =  this.src;
       this.src='blank.gif';
    });
});
sv88
  • 216
  • 1
  • 8
  • This will still load the images. – Pickels Nov 03 '09 at 15:23
  • I just tested it online and your answer is actually correct. This works the same way as removing the src attribute. The reason why it didn't work locally is in the comments of my question. – Pickels Nov 03 '09 at 17:31
1

I don't recommend this solution, for many reasons (like it ruins your page if you don't have Javascript enabled, screen-readers etc), but its a possibility...

You could change the IMG tag so that it hijacks a different attribute, like ALT (LONGDESC, or TITLE too):

Then use Javascript to update the SRC attribute with the ALT value as you need to.

So thats one way, and not a good one. I think the only real approach is to dynamically generate the proper IMG tag as needed via Javascript and not publish it with the HTML (this too has implications for non-JS browsers etc)

donohoe
  • 13,867
  • 4
  • 37
  • 59
  • For my use case by far the best answer, but instead using data attributes, for example: data-cached-src and accessing via element.dataset.cachedSrc. – psquizzle Mar 28 '21 at 07:02
1

This article shows some tests using both css background and img tags on a set of standard browsers.

In my personal experience the PictureFill by Scott Jehl is the best solution I've ever used to deal with image resolutions and sizes for mobile devices.

yahyazini
  • 700
  • 12
  • 23
0

I know this is an old question, but it took me a while to figure out how to accomplish what I wanted to. This is the top result on DuckDuckGo so I think it's worth posting here.

This little snippet will prevent imgs, embeds and iframes from being loaded and will manually load them later when needed. One caveat: objects that are loaded too fast for JQuery/JavaScript to catch them are still loaded, and the script still removes them. Since this is intended to decrease load time this should not be a problem though.

Fiddle

loadObjects = function() {
  /* LOAD OBJECTS */
  $("img, embed, iframe").each(function() {
    var obj = $(this);

    obj.attr("src", obj.data("objsrc")).ready(function() {
      obj.fadeIn(1000, "linear").prev(".loading").fadeOut(750, "linear", function() {
        $(this).remove();
      });
    });
  });
}

$(document).ready(function() {
    /* *** PREVENT OBJECTS FROM LOADING *** */
    $("img, embed, iframe").each(function() {
        var obj = $(this);
        obj.data("objsrc", obj.attr("src"));
        obj.hide().attr("src", "").before("<span class=\"loading\"></span>");
    });
});
bur
  • 604
  • 5
  • 20
0

You can also wrap the image in a template tag:

<template>
  <img src="foo.jpg"/>
</template>

Browsers will not try to load it.

shime
  • 8,746
  • 1
  • 30
  • 51
-1

The answer to this problem is very easy via insertAdjacentHTML() which lets you add HTML when you like, in this case on button click:

function LoadImages(){

 document.body.insertAdjacentHTML('afterEnd','<img src="one.jpg" alt="" height="100" width="100"> <img src="two.jpg" alt="" height="100" width="100">');

}

The HTML...

<button onclick="LoadImages();">Click to load images</button>