Pew Pew Laser Blog

Code. Glass art. Games. Baking. Cats. From Seattle, Washington and various sundry satellite locations.

Pew Pew Laser Blog Archives — by Blog ID

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: code javascript

Authorized users may log-in to leave a comment.

Last Blog: Glass Pumpkin 2009 #3.

Next Blog: Music For Hot Weather.