How do I check if an image has preloaded successfully? [duplicate]
Possible Duplicate:
Check if an image is loaded (no errors) in JavaScript
After being loaded by javascript by setting img.src.
开发者_开发技巧Thanks...!
You can use the load
event like this:
var img = document.getElementById('imgID');
// or
var img = new Image;
img.onload = function(){
alert('The image has been loaded');
img.src = 'image path here';
};
Or when you use the load
event of the window
, images are loaded by then:
window.onload = function(){
// everything is loaded now
};
var myImg = new Image();
myImg.onload = function(){
alert('loaded');
}
myImg.src = '../images/someImage.jpg';
Pure JavaScript (no jQuery) solution is available here for testing: http://jsfiddle.net/Sztxs/1/ (Based on existing answers)
You can integrate this into a function then use that function to preload instead of having to write new onload function for each preloaded image.
You can have whatever you want instead of alert of course.
Let us know if you need any further help. :)
With the help this
var img = new Image();
// Create image
$(img).load(function() {
// Image Loaded notification
}).error(function () {
// Error Notification here
}).attr({
id: "Set Id",
src: "Image Source",
title: "Title Here",
alt: "Alt here"
});
精彩评论