Reputation: 605
I'm changing the content of a div via javascript using myDiv.innerHTML = xmlHttp.responseText
. xmlHttp.responseText
might contain a few images which will be loaded after the div's innerHTML has been changed.
Is there any event which is fired on the div, document or window after those images have completed loading ie after innerHTML of an element has completely loaded?
Upvotes: 3
Views: 2836
Reputation: 490
Well, I went through your question several times again and I came up with this process :
http://jsfiddle.net/Bladepianist/oyv0f7ns/
HTML
<div id="myDiv">Click Me</div>
<div id="myDiv2">Watch</div>
I used two div
so that you could observe the loading of differents images.
JS (No JQuery)
var myDiv = document.getElementById("myDiv");
var myDiv2 = document.getElementById("myDiv2");
var myWatcher = 0;
myDiv.onclick = function () {
var myImage = "<img id='myImage' src='http://getbootstrap.com/assets/img/sass-less.png' style='max-width: 150px;' />";
var myImage2 = "<img id='myImage2' src='http://getbootstrap.com/assets/img/devices.png' style='max-width: 150px;' />";
myDiv.innerHTML = myImage;
myDiv2.innerHTML = myImage2;
// Most important part. Get all the img tags AFTER div was modified.
var myImg = document.getElementsByTagName("img");
// Check if each img is loaded. Second img might be loaded before first.
for (var i = 0; i < myImg.length; i++) {
myImg[i].onload = function () {
myWatcher++;
if (myWatcher == myImg.length) {
alert("All is loaded.");
// Might want to call a function for anything you might want to do.
}
};
}
};
In my example, I used a click event
but the most important part is, of course, the capture of all your img
element right after you modify your DOM.
The for loop allow the add an eventListener (here : onload
) on each img
so that you know when it's loaded.
I have a counter which is incremented when an img
is loaded. When he is equal to myImg.length
it means all's good.
PS (Edit) : Haven't tested on other browsers (just Chrome).
Hope it might help you, even by a little.
Upvotes: 3
Reputation: 358
There is an event, which is fired after the images are completely loaded. So in your ajax request, you can set up an event listener:
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// readyState==4 means "request finished and response is ready"
// status==200 means "everything transferred correctly"
}
}
Upvotes: -1
Reputation: 1254
One way would be to search though responseText
for <img>
and add onload="function()"
. You could do that with responseText.replace(/<img/g,"<img onload=\"function\"")
.
As the comments on the question suggested, another way would be to loop through myDiv.getElementsByTagName("img")
and add an event listener to the "load"
event for each one.
Upvotes: 0