开发者

How do I check if an image has preloaded successfully? [duplicate]

开发者 https://www.devze.com 2023-01-28 08:06 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Check if an image is loaded (no errors) in JavaScript
This question already has answers here: Closed 12 years ago.

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"
});
0

精彩评论

暂无评论...
验证码 换一张
取 消