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.


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')");

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.


Tags: code javascript

Authorized users may log-in to leave a comment.

Last Blog: Glass Pumpkin 2009 #3.

Next Blog: Music For Hot Weather.