I'm loading a fragment of HTML from server side with AJAX, and I'm appending it to the document, and I would like a way to get notified when the fragment is fully added into the dom.
I'm doing something like this:
// Load photos.html from the server with ajax
var instance = loadPageWithAjax('photos.html')
// Wait for response
instance.success = function(response){
// Create Parent Object
// Note that I MUST create a new div in my project
var box = document.createElement('div');
box.id = 'photos-box';
// Insert html response to the box's innerHTML
box.innerHTML = response;
// Append box to the dom
document.body.appendChild(box);
}
And when the fragment is added to the dom I would like to work with the contents in it, but I can't because I don't know when the fragment was actually added into the dom.
I tried to append a script after the response:
document.getElementById('photo-box') = response
+ '<script>alert(\'loaded\')</script>';
It is added but doesn't loads as a script I don't really know why?
Then I tried to append it as a new Object which partly works:
var script = document.createElement('script');
script.type = 'text/javascript';
script.innerHTML = 'alert(\'loaded\')';
document.getElementById('photo-box').appendChild(script);
But it loads faster than the other parts of the fragment.
So what is the right way to get notified when the fragment is added to the dom?
The innerHTML
setter as well as the appendChild
methods are synchronous, so the DOM is updated immediately.
You probably want to be informed when all stylesheets and images are loaded. (innerHTML does not work with scripts)
This is a bit tricky. You're gonna have to iterate over all images and check their loaded
state, then add an onload
handler to each image that has not been loaded.
For stylesheets, it's even more complicated. See yepnope.js for a possible implementation.