Javascript Tips

Javascript has become the scripting language of choice for we browsers since standards are almost universal.

Javascript and AJAX: clean degradation

AJAX (Asynchronous Javascript and X(HT)ML) is a wonderful method of making pages more responsive for sites which require small changes in content. However there are two serious drawbacks.

  1. Browsers with javascript disabled are unable to navigate the site, and
  2. Search engines are unable to index the site.

Current web philosophy dictates that the pages should degrade cleanly into a form which does not require javascript, although some page designers will include the ultimate insult:

<noscript>This site requires javascript.</noscript>

In our practice, we reverse the paradigm, and serve the site in a javascript-disabled form. If javascript is enabled in the browser, we change the menu links dynamically to permit AJAX to be used. Otherwise the site will behave as a standard html-encoded web site.

The document body is coded with a javascript onload procedure:

<body onload="fixAnchors();">

and the following script walks the necessary portions of the document to change the links to a form which allows AJAX to be active using onclick functions:

function fixAnchors() {
var menudivs = ['head','c1','c2','c3','tabs','foot'];
for (var i=0; i < menudivs.length; i++){
var menuElement = document.getElementById(menudivs[i]);
if (menuElement != null) {
var menuElementList = menuElement.getElementsByTagName('a');
for (var j=0; j < menuElementList.length; j++) {
menuElementList[j].setAttribute("href", "#");
}
}
}
} // end function fixanchors

If javascript is disabled, the links are unaltered, and page navigation procedes normally, as does indexing by search engines.

If javascript is enabled, the links are re-written, permitting full AJAX functionality, which becomes active even with pages found from links given by the search engines.

This technique requires a careful page design which will display pages properly without javascript enhancements, and will avoid the two major problems associated with AJAX-enabled pages.