7

Possible Duplicate:
Check if an image is loaded (no errors) in JavaScript

After being loaded by javascript by setting img.src.

Thanks...!

Community
  • 1
  • 1
mtay
  • 1,336
  • 4
  • 20
  • 36

4 Answers4

10

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
};
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
4
var myImg = new Image();

myImg.onload = function(){
   alert('loaded');
}

myImg.src = '../images/someImage.jpg';
theftprevention
  • 5,083
  • 3
  • 18
  • 31
Erik Reppen
  • 4,605
  • 1
  • 22
  • 26
2

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. :)

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
1

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"
});
Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
Vicky
  • 9,515
  • 16
  • 71
  • 88