Child Scripts Making Child Scripts!

I’ve been wrestling with a bug in one of my modules for AIM Pages for_ever_, and just found a fix today. I created this well-intentioned module called code snippet that allows you to paste in markup and it’ll get inserted into the DOM. This is really just a stopgap to allow people to add stuff that a module doesn’t exist for yet. I never should have written it. Do you know how bad DOM support is in IE? It’s awful!\
The big problem is that people wanted/needed to insert script elements with inline script using the code snippet module, and I couldn’t figure out a good way to do it (ok, any way, good or otherwise). Just adding them to the DOM using innerHTML doesn’t work. IE won’t allow you to create a new script element and set the text content to the code.\
Today, I stumbled on a message board post that hints at the answer. What’s the answer?\
Create a new script element, and set the text property to the script content and then append it to the body. Voila, actual evaluated javascript! Here’s an example:

<code>var b=document.getElementsByTagName("body")[0];
var txt="function doIt(msg) {alert(msg)}";
var scr=document.createElement("script");
scr.setAttribute("type","text/javascript");
scr.text=txt;
b.appendChild(scr);</code>

Enjoy! Oh, and the fixed version of the module isn’t live yet. I’m letting the QA guys look at it first before I unleash it on an unsuspecting world.

By Kevin Lawver

Web developer, Software Engineer @ Gusto, Co-founder @ TechSAV, husband, father, aspiring social capitalist and troublemaker.

3 comments

  1. You can also use the defer attribute in the script tag, as in
    <script defer type=”Javascript”>
    Although this is defined in the WC3 DOM and works fine in MSIE as of V4, the Mozilla engine (FF, NN, etc.) does not appear to support it.

  2. I think Gecko does support defer as long as it’s more like this:
    <script type=”text/javascript” defer=”defer” src=”somescript.js”></script>

  3. I am used to do this in a similar way:
    document.body.insertBefore( script , document.body.firstChild );
    Kevin, it was comforting seeing another way of doing this, I started to believe just me being crazy needing this kind of things… 🙂
    It seems this avoid a lot of problems in IE where one still doesn’t know where the parser insertion point is up to…( at load time for me ).
    And the insertAfter clone may be used to overwrite and emulate “document.write” in XHTML documents.

Comments are closed.