Prevent images from loading

Viewed 59026

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.

11 Answers

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>");
    });
});

You can also wrap the image in a template tag:

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

Browsers will not try to load it.

Related