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"))
;
Hope this helps!
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.
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. :-)
Detect when an image fails to load in JavaScript
You could try the following code. I can't vouch for browser compatibility though, so you'll have to test that.
function testImage(URL) {
var tester=new Image();
tester.onload=imageFound;
tester.onerror=imageNotFound;
tester.src=URL;
}
function imageFound() {
alert('That image is found and loaded');
}
function imageNotFound() {
alert('That image was not found.');
}
testImage("http://foo.com/bar.jpg");
And my sympathies for the jQuery-resistant boss!
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
Check if image exists without loading it
Since JavaScript (and therefore jQuery) is client-side and the image resides server-side before loading there is no way to check to see if the image exists without using Ajax or your server-side scripting to make sure the image exists.
Detect image load
You can use the .load()
event handler, like this:
$("#myImg").load(function() {
alert('I loaded!');
}).attr('src', 'myImage.jpg');
Be sure to attach it before setting the source, or the event may have fired before you attached a handler to listen for it (e.g. loading from cache).
If that's not doable (setting the src
after binding), be sure to check if it's loaded and fire it yourself, like this:
$("#myImg").load(function() {
alert('I loaded!');
}).each(function() {
if(this.complete) $(this).load();
});
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.
Related Topics
How to Manage a Redirect Request After a Jquery Ajax Call
Weird Behavior With Objects & Console.Log
"Cross Origin Requests Are Only Supported For Http." Error When Loading a Local File
What Is the !! (Not Not) Operator in JavaScript
Http Get Request in JavaScript
Onclick or Inline Script Isn't Working in Extension
How to Debug My JavaScript Code
Use of 'Prototype' Vs. 'This' in JavaScript
Safely Turning a Json String into an Object
Methods in Es6 Objects: Using Arrow Functions
How to Calculate Number of Days Between Two Dates
Why Is Extending Native Objects a Bad Practice
Why Is Settimeout(Fn, 0) Sometimes Useful
A Partial View Passing a Collection Using the Html.Begincollectionitem Helper
How to Access the Matched Groups in a JavaScript Regular Expression
How to Loop Through a Plain JavaScript Object With the Objects as Members