I am trying to add a script block dynamically to the document. When I do this, the script block is not getting executed.
<body>
<div id="dynamicDiv">
</div>
<script type="text/javascript">
var elem = document.getElementById("dynamicDiv");
var tmpStr = "<script type="text/javascript"> ";
tmpStr += "function hello (val)";
tmpStr += "{";
tmpStr += "alert('hello ' + val);";
tmpStr += "}";
tmpStr += "</script>";
elem.innerHTML = tmpStr;
hello("World");
</script>
</body>
The above code does not work. From another post (How do you execute a dynamically loaded JavaScript block?), I saw a reply that if script is added to innerHTML, it will not be executed. Instead of directly using innerHTML, create a div with this innerHTML and use appendChild to add the script.
<body>
<div id="dynamicDiv">
</div>
<script type="text/javascript">
var elem = document.getElementById("dynamicDiv");
var tmpStr = "<script type="text/javascript"> ";
tmpStr += "function hello (val)";
tmpStr += "{";
tmpStr += "alert('hello ' + val);";
tmpStr += "}";
tmpStr += "</script>";
var newdiv = document.createElement('div');
newdiv.innerHTML = tmpStr;
elem.appendChild(newdiv);
hello("World");
</script>
</body>
How ever, this solution also did not work for me.
In another reply, I again saw that we should get the script elements and execute them using eval.
<body>
<div id="dynamicDiv">
</div>
<script type="text/javascript">
var elem = document.getElementById("dynamicDiv");
var tmpStr = "<script type="text/javascript"> ";
tmpStr += "function hello (val)";
tmpStr += "{";
tmpStr += "alert('hello ' + val);";
tmpStr += "}";
tmpStr += "</script>";
var newdiv = document.createElement('div');
newdiv.innerHTML = tmpStr;
elem.appendChild(newdiv);
var scripts = newdiv.getElementsByTagName('script');
for (var ix = 0; ix < scripts.length; ix++) {
eval(scripts[ix].text);
}
hello("World");
</script>
</body>
This solution works for me.
But if do this in a function then it does not work.
<body>
<div id="dynamicDiv">
</div>
<script type="text/javascript">
function createFunction(){
var elem = document.getElementById("dynamicDiv");
var tmpStr = "<script type="text/javascript"> ";
tmpStr += "function hello (val)";
tmpStr += "{";
tmpStr += "alert('hello ' + val);";
tmpStr += "}";
tmpStr += "</script>";
var newdiv = document.createElement('div');
newdiv.innerHTML = tmpStr;
elem.appendChild(newdiv);
var scripts = newdiv.getElementsByTagName('script');
for (var ix = 0; ix < scripts.length; ix++) {
eval(scripts[ix].text);
}
hello("World 1");
}
createFunction();
hello("World 2");
</script>
</body>
I can see that the function is available after the script is evaled. and is available in the function createFunction. Outside createFunction() scope, hello() is not available.
What am I doing wrong? Am I missing something very basic? Please check and help.
Thanks,
Paul
P.S. I don't use jQuery.
I am using chrome to test this.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…