HOWTO: Add JavaScript to a Web Page Programmatically.
I just have to damned well rant about this because people are killing me. Dealing with Google stuff of late, they don't even seem to do it consistently across products. The Google Ajax Loader actually does this properly, but it loads other scripts that don't (Maps! I am looking at you!)
The Problem
document.write(). This method is a holdover from the original Nescape 3.0 browser implementation and it was pretty damned stupid even back then. This was a method that let you push new text content into the parse stream of the browser before the page was rendered. So:
Hello World!
Would draw the date on the screen. The problem is, this can only be evaluated at PARSE time. Subsequent calls to document.write will completely demolish the existing document. Moreover, for newer browsers that have XML/XHTML support, anything that is defined as strict XML, document.write kills the whole thing, because you can't push text into the stream that is being parsed.
Why should you care? Because if someone wants to include your shitty shitty JavaScript file on their page, and not wait for your shitty shitty web server to return it before letting the user, you know, do something, they will likely set defer='defer' on their page. This is something that, like XML, post-dates document.write, and means that all evaluation of that script will be delayed until after the page parse execution context has been released.
The Solution
Try to behave well. Use the DOM APIs and add your script to the head of the document, but if that isn't there, because the HTML monkey was stupid and/or lazy, add it to the body. D.W should be your last line of defense.
function AddScriptTag(src) { var node = document.getElementsByTagName("head")[0] || document.body; if(node){ var script = document.createElement("script"); script.type="text/javascript"; script.src=src node.appendChild(script); } else { document.write(""); } }
Thank you. This has been a public service rant.








Comments
hello
Thanks, for the good articles...I am very intiresting..