I am changing src for image dynamically and want to capture on load event for that image. Is there a way I can do it?
2 Answers
Several years ago, I discovered that the onload event was not reliable in some browsers (I don't remember which ones) when setting .src
for the second time. As such, I settled for replacing the image object. I would create a new image object, set the onload handler, set the .src
value and then when it loads, insert it into the page in place of the existing image.
When creating an image from scratch in javascript, you do this:
var img = new Image();
img.onload = function() {
// put your onload code here
};
img.src = "xxx.jpg"
If you just want to change the .src
of an image, you just find the DOM object in the page and set it's .src
property.
var img = document.getElementById("myImage");
img.src = "xxx.jpg";
If you want to try to capture the onload event when resetting the .src
(what I had reliability problems with a couple years ago, you would do this:
var img = document.getElementById("myImage");
img.onload = function() {
// your code here
};
img.src = "xxx.jpg";
If you want to load a new image and replace an existing one with it when it loads, you would do this:
function replaceImg(oldImage, newSrc) {
var img = new Image();
img.onload = function() {
var parent = oldImage.parentNode;
parent.insertBefore(img, oldImage);
parent.removeChild(oldImage);
// put any other code you want here when the
// replacement image is loaded and in place
};
img.src = newSrc;
}
And, you would call this like this:
<img id="myImage" src="yyy.jpg">
var oldImage = document.getElementById("myImage");
replaceImg(oldImage, "xxx.jpg");

- 683,504
- 96
- 985
- 979
// create image object
var image = new Image();
image.onload = function () {
// do stuff
$('#myimageelementid').prop('src', image.src); // set the element in the DOM with this image
}
image.src = "image.jpg"; // will trigger onload when loaded

- 49,577
- 28
- 142
- 181