Prevent large image flickering on src change

supersize picture supersize · May 24, 2013 · Viewed 12.3k times · Source

I've a problem with image flickering with large images. In my body i have 5 images:

<img id="img1" src="img1.png" width="250">
<img id="img2" src="img2.png" width="250">
<img id="img3" src="img3.png" width="250">
<img id="img4" src="img4.png" width="250">
<img id="img5" src="img5.png" width="250">

and one I'm dragging one of them with jQuery UI, all are changing their src and on dragend as well:

function dragStart() {
        $('#img2').attr('src','newimg2.png');
        $('#img3').attr('src','newimg3.png');
        $('#img4').attr('src','newimg4.png');
        $('#img5').attr('src','newimg5.png'); }

so fine so good. But I need to use large images (2000 x 2000px) because all images can be clicked and then they will animate to the full size of the viewport that they dont pixelate.

$this.animate(
                { width: 1800, top: -650, left: -250 }, 

                {
                    duration: 4000,
                    easing: 'easeOutElastic'
                }) 

I think because of the size of every image, they are flickering. Does anyone of you have an idea how to prevent this flickering on images, if all src change at the same time ?

Thanks for your effort

Answer

S&#233;bastien Renauld picture Sébastien Renauld · May 24, 2013

The key to what you are trying to do is called preloading. However, you'll need to think carefully about how you want to do this.

Preloading involves loading the image in an img tag off-screen, but still in the DOM. This caches the image locally, which means that the next time you attempt to use the same source, it'll pull from cache instead of querying the server for the image (and, thus, flicker).

Preloading an image is a simple matter:

(new Image()).src="mysource.png";

What you want to decide is when you want to load the images. IF you load them all at first, you'll potentially use up a lot of bandwidth. If you load them on-click, you'll get buffering.

You can check if an image is loaded using the onload event present on img tags and wrapped within jQuery if needed, as follows:

var i = new Image();
i.onload = function() {
  console.log("Loaded");
}
i.src = "mysource.png";

Credits to Robin Leboeuf for the concise Image() form.