I’ve built a modal image gallery. When the user clicks next to see next image I run something like:
document.getElementById('gallery-image').src = newSRC;
My problem is that there is a delay from when the user clicks next to where the image actually changes. (due to the new image being loaded). I want to “empty” the image element the moment the user clicks next. I tried doing this:
document.getElementById('gallery-image').src = '';
setTimeout(function(){
document.getElementById('gallery-image').src = newSRC;
}, 100);
to no avail.
How can I “empty” the IMG element until the new image starts loading on it?
There are three main ways to do this. Your question seemed to suggest you want to create an effect similar to a slide projector changing slides, so I have written this answer with that in mind.
Temporarily set the
srcproperty to a 1×1 transparent GIF instead of the empty string. This is most similar to what you tried to do and perhaps is the simplest method.The data URI below is from Blank image encoded as data-uri and should work in Internet Explorer 8 or higher and the other major browsers. Using a data URI avoids the need to store a separate file on your web server and preload it when your page loads. You may need to set the
widthandheightattributes of the img element to preserve the layout of your page.This code does not preload the image at the start of the time delay (although it would be possible to do so), thus the apparent delay to the viewer is the sum of the programmed time delay and the time taken to load the image. The loading time will only be close to zero if the browser has already cached the image or if the web server is on the local network.
Temporarily set
display: none;, and use anonloadfunction to undo the change once the time delay has elapsed and the image has loaded. The code below starts loading the image at the start of the time delay, which depending on the viewer’s connection speed, may result in a more consistent apparent delay.Do the above, but set
visibility: hidden;instead. This may have the advantage of not affecting the page layout wheredisplay: none;would.