Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't load hidden images

I have a bunch of hidden images on my website. Their container DIVs have style="display: none". Depending on the user's actions, some images may be revealed via javascript. The problem is that all my images are loaded upon opening the page. I would like to put less strain on the server by only loading images that eventually become visible. I was wondering if there was a pure CSS way to do this. Here are two hacky/complicated ways I am currently doing it. As you can see, it's not clean code.

<div id="hiddenDiv">
   <img src="spacer.gif" />
</div>

.reveal .img {
 background-image: url(flower.png);
}

$('hiddenDiv').addClassName('reveal');

Here is method 2:

<img id="flower" fakeSrc="flower.png" />

function revealImage(id) {
 $('id').writeAttribute(
  'src',
  $('id').readAttribute('fakeSrc')
 );
}

revealImage('flower');
like image 932
JoJo Avatar asked Sep 29 '10 00:09

JoJo


People also ask

Does the browser load hidden images?

Even today (oct 2017), the most common browser Chrome will download all 'img' element sources, even if they're hidden. It won't download hidden background images.

Does display none prevent loading?

Images or wrapper elements that have display: none set, will still get loaded. So if you want to eg. load a different image for desktop and mobile, you can either: use display: none , but with the loading="lazy" parameter set on img .

How can I hide my photos in Mobile?

Open the Gallery app and find a photo you want to hide. Tap and hold to select it and tap the three vertical dots at the bottom right. Choose Move to Secure Folder from the drop-down list.


3 Answers

The browser will load any images that has a src attribute set, so what you want to do is to use data-src in the markup and use JavaScript to set the src attribute when you want it to load.

<img class="hidden" data-src="url/to/image.jpg" />

I created this tiny plugin that will take care of the problem:

(function($){
    // Bind the function to global jQuery object.
    $.fn.reveal = function(){
        // Arguments is a variable which is available within all functions
        // and returns an object which holds the arguments passed.
        // It is not really an array, so by calling Array.prototype
        // he is actually casting it into an array.
        var args = Array.prototype.slice.call(arguments);

        // For each elements that matches the selector:
        return this.each(function(){
            // this is the dom element, so encapsulate the element with jQuery.
            var img = $(this),
                src = img.data("src");

            // If there is a data-src attribute, set the attribute
            // src to make load the image and bind an onload event.
            src && img.attr("src", src).load(function(){
                // Call the first argument passed (like fadeIn, slideIn, default is 'show').
                // This piece is like doing img.fadeIn(1000) but in a more dynamic way.
                img[args[0]||"show"].apply(img, args.splice(1));
            });
        });
    }
}(jQuery));

Execute .reveal on the image(s) you want to load/show:

$("img.hidden").reveal("fadeIn", 1000);

See test case on jsFiddle.

like image 59
mekwall Avatar answered Oct 18 '22 18:10

mekwall


Here's a jQuery solution:

$(function () {
   $("img").not(":visible").each(function () {
       $(this).data("src", this.src);
       this.src = "";
   });

   var reveal = function (selector) {
       var img = $(selector);
       img[0].src = img.data("src");
   }
});

It's similar to your solution, except it doesn't use the fakeSrc attribute in the markup. It clears the src attribute to stop it from loading and stores it elsewhere. Once you are ready to show the image, you use the reveal function much like you do in your solution. I apologize if you do not use jQuery, but the process should be transferable to whichever framework (if any) that you use.

Note: This code specifically must be ran before the window has fired the load event but after the DOM has been loaded.

like image 37
Cristian Sanchez Avatar answered Oct 18 '22 20:10

Cristian Sanchez


It partially depends on how your images must be placed in your code. Are you able to display the images as the background of a <div>, or are you required to use the <img> tag? If you need the <img> tag, you may be screwed depending on the browser being used. Some browsers are smart enough to recognize when an image is inside of a hidden object or in an object of 0 width/height and not load it since it's essentially invisible, anyway. For this reason many people will suggest putting an image in a 1x1 pixel <span> if you want the image to be pre-loaded but not visible.

If you don't require the <img> tag, most browsers won't load images referenced by CSS until the element in question becomes visible.

Mind you that short of using AJAX to download the image there's no way to be 100% sure the browser won't pre-load the image anyway. It's not unbelievable that a browser would want to pre-load anything it assumes may be used later in order to "speed up" the average load times.

like image 2
stevendesu Avatar answered Oct 18 '22 19:10

stevendesu