Search code examples
javascriptappendchild

Why 'inject with insertBefore avoid appendChild errors'?


On the article How, When, And Why Script Loaders Are Appropriate, I found the following comment without a clear explanation:

// Very simple asynchronous script-loader

// Create a new script element
var script      = document.createElement('script');

// Find an existing script element on the page (usually the one this code is in)
var firstScript = document.getElementsByTagName('script')[0];

// Set the location of the script
script.src      = "http://example.com/myscript.min.js";

// Inject with insertBefore to avoid appendChild errors
firstScript.parentNode.insertBefore( script, firstScript );

What errors they are avoiding by using insertBefore instead of appendChild?

Why would appendChild cause any errors?


Solution

  • Looks like it's for a bug in IE6, and to avoid problems with the absence of a head tag.

    Good description for script injection techniques and a little bit of history and context: http://www.stevesouders.com/blog/2010/05/11/appendchild-vs-insertbefore/

    Specifically this issue: https://bugs.jquery.com/ticket/2709

    head = document.getElementsByTagName ("head")[0] || 
        document.documentElement;
    // Use insertBefore instead of appendChild to circumvent an IE6 bug.
    // This arises when a base node is used (#2709 and #4378).
    head.insertBefore(script, head.firstChild);
    

    Incidentally I've had to do a lot of work on IE6 support, and I've never had this problem. I avoided using the head tag for other reasons and used insertBefore so it would be easier to clean up injected scripts when needed, so I guess I just got lucky.