On my album slide show page, i have code like
<span style="display:none;"> <img id="id1" src="~$imageUrl`" onload="javascript:showImage();"> </span> <span> // show loader. </span>
in showImage()
, i am sure the image is loaded, so i show the image and hide the loader.
Now when user clicks on next, i need to change the src of the image. Now i need don't know how to set src only when image is loaded.
Create Image Element in JavaScriptCreate an image element using the createElement() method on the document object. Then, set an image URL to its src attribute. Finally, add the image element to the DOM hierarchy by appending it to the body element.
Image() The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document. createElement('img') .
you can just append another hidden img
element and swap them in onload
event.
Or use single image element and use javascript like:
var _img = document.getElementById('id1'); var newImg = new Image; newImg.onload = function() { _img.src = this.src; } newImg.src = 'http://whatever';
this code should preload the image and show it when it's ready
Sorry guys.
You can't rely on the image load event to fire but you can kind of rely on it in some situations and fallback to a maximum load time allowed. In this case, 10 seconds. I wrote this and it lives on production code for when people want to link images on a form post.
function loadImg(options, callback) { var seconds = 0, maxSeconds = 10, complete = false, done = false; if (options.maxSeconds) { maxSeconds = options.maxSeconds; } function tryImage() { if (done) { return; } if (seconds >= maxSeconds) { callback({ err: 'timeout' }); done = true; return; } if (complete && img.complete) { if (img.width && img.height) { callback({ img: img }); done = true; return; } callback({ err: '404' }); done = true; return; } else if (img.complete) { complete = true; } seconds++; callback.tryImage = setTimeout(tryImage, 1000); } var img = new Image(); img.onload = tryImage(); img.src = options.src; tryImage(); }
use like so:
loadImage({ src : 'http://somewebsite.com/image.png', maxSeconds : 10 }, function(status) { if(status.err) { // handle error return; } // you got the img within status.img });
Try it on JSFiddle.net
http://jsfiddle.net/2Cgyg/6/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With