I am trying to add a script block dynamically to a document. When I do this, the script block is not 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 code above does not work. From another post ( How do you execute a dynamically loaded JavaScript block? ), I saw the answer that if a script is added to innerHTML, it will not be executed. Instead of using innerHTML directly, create a div with this innerHTML and use appendChild to add a 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>
Be that as it may, this solution also did not work for me.
In another answer, 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 you do this in a function, then it wonβt 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 see that the function is available after the script value is changed. and is available in the createFunction function. Outside the scope of createFunction (), hello () is not available.
What am I doing wrong? Did I miss something? Please check and help.
Thanks Paul
PS I do not use jQuery. I use chrome to check this out.