Dynamically Adding a JavaScript Element.
7.21.2010
This bit of JavaScript will allow you to dynamically add a JavaScript element (which will execute) into a document's head.
var theScript = document.createElement("script");
theScript.type = "text/javascript";
theContent = document.createTextNode("alert('hi')");
theScript.appendChild(theContent);
document.getElementsByTagName("head")[0].appendChild(theScript);
First, we prepare a new script element using createElement(). We then create the text that will be our executing JavaScript, and insert it into the script element. Last, we append the new script element to the end of the first head element in the document.
Why would we want to use JavaScript to edit the HTML to add JavaScript? Clients.
Permalink
Tags: javascript web-designAuthorized users may log-in to leave a comment.