khizar ansari
khizar ansari

Reputation: 1556

javascript is not working if i add dynamic script tag

i want to add dynamic javascript tag on the body

window.onload = function() {
     var e = document.createElement('span');
     e.innerHTML ='<script type="text/javascript">alert("hello");</script>';
     document.body.insertBefore(e,document.body.childNodes[0]);                
}

in the above example the javascript which is being loaded using innerHTML is not working

is there any workaround for this problem

Upvotes: 0

Views: 81

Answers (1)

Christoph
Christoph

Reputation: 51181

The clean way would be the following:

var e = document.createElement('script');
e.type = "text/javascript";  // not needed in HTML5
e.innerHTML ='alert("hello");'; // or .text or create a new textnode

document.body.appendChild(e);

Upvotes: 1

Related Questions