Skip navigation.

Claws, fangs, fur...

...the bear essentials

Adding javascript to a real xhtml page, unobtrusively

Death to document.write()!

Why should we kill the trustful document.write()? It's been around for ages and serves good purpose in lots of web sites!

It's because Google Maps and other web sites continue to use document.write() in XHTML pages, where it is harmful to the web pages and destroys functionality. Google Maps also uses it in their examples, teaching new script adepts wrong techniques. (Outlined in this other article.)

(By the way: the problem is not in the XHTML... nor is it in using document.write() in application/xhtml+xml, as in that mime type the browser simply refuses to execute it. No, the problem is in text/html, where it bloody well overwrites the current document. Wyciwyg...)

There is a different way.

The document.createElement() function (javascript, DOM 1) can create a script element. (Of course, once created and identified, we can reuse the same script element over and over again.) Using element.setAttribute() we can assign a script source. Then we append the new script to the document and we're set.

Here's the code, which I succesfully applied in a different page on my site, including a call-back inside the external script... resulting in a complete and utter annihilation of AJAX-need. :D

if ((document)&&(document.createElement)) {
 var theNewScript = document.createElement('script');
 if ((theNewScript)&&(theNewScript.setAttribute)) {
  theNewScript.setAttribute('id','myNewScript');
  theNewScript.setAttribute('type','text/javascript');
  theNewScript.setAttribute('src','http://domain/dir/script.js');
 }
 if (document.body.appendChild) {
  document.body.appendChild(theNewScript);
 } else if (document.documentElement.appendChild) {
  document.documentElement.appendChild(theNewScript);
 } else if (document.appendChild) {
  document.appendChild(theNewScript);
 }
}


Oh yeah. The script you inject this way, should not contain any document.write() statements itself... In application/xhtml+xml they won't work, and in text/html they may overwrite the entire document... I created a test case for this specific issue:
http://www.omegajunior.net/code/javascriptinjection.php

Happy coding!

Cross-browser pop-undersI hate MSIE (yet again)

Write a comment

You must be logged in to write a comment. If you're not a registered member, please sign up.

Download Opera, the fastest and most secure browser