Check if an image is loaded (no errors) with jQuery
Another option is to trigger the onload
and/or onerror
events by creating an in memory image element and setting its src
attribute to the original src
attribute of the original image. Here's an example of what I mean:
$("<img/>")
.on('load', function() { console.log("image loaded correctly"); })
.on('error', function() { console.log("error loading image"); })
.attr("src", $(originalImage).attr("src"))
;
How can I determine if an image has loaded, using Javascript/jQuery?
Either add an event listener, or have the image announce itself with onload. Then figure out the dimensions from there.
<img id="photo"
onload='loaded(this.id)'
src="a_really_big_file.jpg"
alt="this is some alt text"
title="this is some title text" />
jQuery or Javascript check if image loaded
I usually do this:
var image = new Image();
image.onload = function () {
console.info("Image loaded !");
//do something...
}
image.onerror = function () {
console.error("Cannot load image");
//do something else...
}
image.src = "/images/blah/foo.jpg";
Remember that the loading is asynchronous so you have to continue the script inside the onload and onerror events.
Check if images are loaded?
The text from the .ready jQuery docs might help make the distinction between load
and ready
more clear:
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.
... and from the .load docs:
The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
So .load
is what you're looking for. What's great about this event is that you can attach it to only a subset of the DOM. Let's say you have your slideshow images in a div like this:
<div class="slideshow" style="display:none">
<img src="image1.png"/>
<img src="image2.png"/>
<img src="image3.png"/>
<img src="image4.png"/>
<img src="image5.png"/>
</div>
... then you could use .load
just on the .slideshow
container to trigger once all of the images in the container have been loaded, regardless of other images on the page.
$('.slideshow img').load(function(){
$('.slideshow').show().slideshowPlugin();
});
(I put in a display:none
just as an example. It would hide the images while they load.)
Update (03.04.2013)
This method is deprecated since jQuery Version 1.8
JQuery - Check when image is loaded?
The load
event of an image is fired when it's loaded (doh!), and critically, if you don't hook up your handler before it loads, your handler won't get called. Browsers will load resources in parallel, so you can't be sure (even in jQuery's ready
event saying the page's DOM is ready) that the image hasn't already been loaded when your code runs.
You can use the complete
property of the image object to know whether it's already been loaded, so:
var firstPhoto = $("#photos img:first");
if (firstPhoto[0].complete) {
// Already loaded, call the handler directly
handler();
}
else {
// Not loaded yet, register the handler
firstPhoto.load(handler);
}
function handler() {
alert("Image loaded!");
}
There may even be a race condition in that, if the browser in question really implements multi-threaded loading where the image load may occur on a different thread than the Javascript thread.
Of course, if your selector will match multiple images, you'll need to handle that; your selector looks like it's supposed to match only one, so...
Edit This version allows for multiple images, and I think it handles any non-Javascript race conditions (and of course, at present there are no Javascript race conditions; Javascript itself is single-threaded in browsers [unless you use the new web workers stuff]):
function onImageReady(selector, handler) {
var list;
// If given a string, use it as a selector; else use what we're given
list = typeof selector === 'string' ? $(selector) : selector;
// Hook up each image individually
list.each(function(index, element) {
if (element.complete) {
// Already loaded, fire the handler (asynchronously)
setTimeout(function() {
fireHandler.call(element);
}, 0); // Won't really be 0, but close
}
else {
// Hook up the handler
$(element).bind('load', fireHandler);
}
});
function fireHandler(event) {
// Unbind us if we were bound
$(this).unbind('load', fireHandler);
// Call the handler
handler.call(this);
}
}
// Usage:
onImageReady("#photos img:first");
A couple of notes:
- The callback doesn't get the
event
object; you could modify it to do so if you liked, but of course, there'd be no event in the case where the image is already loaded, so it would be of limited utility. - You could probably use
one
instead ofbind
andunbind
, but I like the clarity and I'm paranoid. :-)
JavaScript: Know when an image is fully loaded
Sure. Remember the load needs to be added before the src attribute.
$('<img />').load( function(){
console.log('loaded');
}).attr('src', imgUrl);
If you have defined the image tag in the markup then your stuck with when the window load event fires to be sure the image has come down the wire.
Detecting when an image has loaded
You can use image.onload = function(){<...>}
;
Image is the actual image you want to get the load of.
<img src='...' id='image'>
In order to check if the image finished loading do the following->
document.getElementById('image').onload = function(){<...>}
or
document.getElementById('image').addEventListener('load',function(){<...>},false);
If you want to check if the image failed to load do this->
document.getElementById('image').onerror = function(){<...>}
or
document.getElementById('image').addEventListener('error',function(){<...>},false);
Note
.addEventListener
method won't work in IE8. If you are planning on supporting it I can edit my answer.
How do I check if an already loaded image has loaded in JavaScript?
I think you're looking for the solution provided here :
How to tell if an image is loaded or cached in JQuery?
Basically, check the ".complete" property of the image object.
Related Topics
JavaScript Can't Find Element by Id
How to Reset <Input Type = "File">
Event Delegation VS Direct Binding When Adding Complex Elements to a Page
JavaScript .Replace Command Replace Page Text
Returning a Value from Callback Function in Node.Js
Calling Setstate in a Loop Only Updates State 1 Time
Inspect Attached Event Handlers for Any Dom Element
Pass Arguments with Page.Evaluate
Undefined Values in Array(Len) Initializer
Is Reading the 'Length' Property of an Array Really That Expensive an Operation in JavaScript
Check If Jquery Has Been Loaded, Then Load It If False
How to Set a Js Object Property Name from a Variable
Is a JavaScript Array Index a String or an Integer
Jasmine: Async Callback Was Not Invoked Within Timeout Specified by Jasmine.Default_Timeout_Interval