Reputation: 168101
I have a DOM object that is inserted into an existing HTML document by AJAX. I want to embed an inline script in the inserted object so that it will be executed right after it becomes part of the HTML document. The following is my attempt, and it is to be inserted into an existing HTML document by AJAX, but it does not work. What is the right way to do it?
<div onload='alert(self.offsetWidth);'>Foo</div>
Upvotes: 0
Views: 446
Reputation: 179
If you really need to execute something on node insertion, MutationObserver
is the way to go (with slooow and deprecated MutationEvent
s for older browsers). It’s often an overkill, affects performance of your application (some argue mutation events ruin performance), which makes DOM mutations watching not the best idea whatsoever (if you can, don’t miss better options, like including your code into XHR onload proposed above).
Upvotes: 0
Reputation: 707318
A div element does not have an onload
event so that's why your current technique does not work.
What other libraries (like jQuery) do to execute scripts in dynamically loaded code is they load the HTML, insert it into the document and then they find the script tags that are embedded in it, then dynamically re-insert those script tags into the document which causes them to get loaded and evaluated.
Here's a short example:
// dynamically inserted content example
var html = "<script>console.log('hello');<" + "/script" + "><div>Hi</div>";
// insert content
var obj = document.getElementById("test")
obj.innerHTML = html;
// now make a copy of the script tag and re-insert it into the document
// to get it processed
var head = document.getElementsByTagName("head")[0];
var scripts = obj.getElementsByTagName("script");
var s;
for (var i = 0; i < scripts.length; i++) {
s = scripts[i];
s.parentNode.removeChild(s);
var newScript = document.createElement("script");
newScript.innerHTML = s.innerHTML;
head.appendChild(newScript);
}
Working demo: http://jsfiddle.net/jfriend00/BcL34/
If all you really need to now is when your ajax code has finished loading the new content, then you can simply call a callback function from your ajax code after it finishes inserting the content and that callback function can then carry out your action.
Upvotes: 1