Unobtrusive JavaScripts

All of the unobtrusive JavaScripts you can download from this site work the same way.

In each script there will be one or two JavaScript files and a stylesheet file that need to be attached into the head of your page. The resultant code will always look something like this:

<script type="text/javascript" src="scriptname.js"></script>
<link rel="stylesheet" type="text/css" href="scriptname">

There will also be a section of HTML that you will need to insert into your page which could be anything from an id attribute to add to one of your existing tags to a complete form to be inserted. Any HTML to be inserted assumes that you are using a strict HTML 4.01 doctype for your page.

Each of these scripts uses a loop within the JavaScript to test when the appropriate ids have been loaded into the page so as to run the JavaScript needed to update those tags (the unobtrusive JavaScript processing). The following is the code used to do this:

var pageLoaded = 0;
window.onload = function() {pageLoaded = 1;}
function loaded(i,f) {
if (document.getElementById && document.getElementById(i) != null) f();
else if (!pageLoaded) setTimeout('loaded(\''+i+'\','+f+')',100);

If you are incorporating multiple of these scripts into the same page then you only need this section of code once. If you are incorporating other scripts that use window.onload then you need to change the processing in those other scripts to use the loaded() functipon instead. This function takes two parameters, the second parameter is the function to run when the id specified in the first parameter has loaded into the page. Using the loaded() function will get your code running as soon as possible rather than waiting for the whole page to load.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow