Prevent images from loading
Asked Answered
J

11

42

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.

Jacqualinejacquard answered 3/11, 2009 at 15:1 Comment(5)
I've amended my answer to address your edit.Nimesh
Thanks, I commented your answer.Jacqualinejacquard
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).Nimesh
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.Jacqualinejacquard
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.Nimesh
N
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" />
Nimesh answered 3/11, 2009 at 15:4 Comment(6)
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?Jacqualinejacquard
Sorry, I lost site of the original question. It looks like your answer is here: $(self).removeAttr("src"); self.loaded = false;Nimesh
$("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.Vallejo
This doesn't work work anymore in latest browsers. eg. chrome 12 :(Faery
@Faery 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.Nimesh
@Nimesh 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 :)Faery
P
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.

Plast answered 31/12, 2013 at 21:11 Comment(4)
It does work and requires no change to the HTML of the image element itself. Voting for this as best answer. One possible solution is to use <script type="some/thing">, although <noscript> is better option if you want to have fallback for noJS.Zeus
Almost what I need. $('<noscript><div><img src="fo2o.png"></div></noscript>').html() works, but $('<noscript>').append('<div><img src="fo2o.png"></div></noscript>').html() does not :-(Lydia
Strangely, $('<noscript>').append('<img>').find('img').attr('src','foo.png') also causes the image to be loaded.Lydia
If this works, it would be wonderful for progressive enhancementAbrade
N
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" />
Nimesh answered 3/11, 2009 at 15:4 Comment(6)
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?Jacqualinejacquard
Sorry, I lost site of the original question. It looks like your answer is here: $(self).removeAttr("src"); self.loaded = false;Nimesh
$("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.Vallejo
This doesn't work work anymore in latest browsers. eg. chrome 12 :(Faery
@Faery 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.Nimesh
@Nimesh 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 :)Faery
T
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.

Tarantass answered 3/11, 2009 at 15:4 Comment(2)
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.Rachealrachel
@Rachealrachel Point the indexer bot to a different page which is suitable for robots.Tarantass
P
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.

Photoelectrotype answered 3/11, 2009 at 15:34 Comment(0)
C
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

Caldeira answered 3/11, 2009 at 15:6 Comment(1)
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.Jacqualinejacquard
E
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';
    });
});
Enceladus answered 3/11, 2009 at 15:19 Comment(2)
This will still load the images.Jacqualinejacquard
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.Jacqualinejacquard
A
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)

Arboreous answered 3/11, 2009 at 15:49 Comment(1)
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.Ferris
S
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.

Stallfeed answered 17/2, 2015 at 20:21 Comment(0)
A
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>");
    });
});
Atahualpa answered 18/10, 2016 at 18:27 Comment(0)
G
0

You can also wrap the image in a template tag:

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

Browsers will not try to load it.

Gripsack answered 1/7, 2020 at 5:29 Comment(0)
E
-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>
Englishman answered 11/3, 2018 at 13:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.