Faster DOM Access
Join the Discussion
One of the biggest problems with updating a web page from Javascript is that in order to access the parts of the page using the Document Object Model you first have to wait for that part of the page to be actually loaded first. The biggest problem with this is that the only time that Javascript has of telling that the page has loaded is via the window.onload event handler which is triggered when the whole page (including all the images) have finished loading. If your page has a number of images on it that slow the page loading then you are also delaying the updates that Javascript could have done earlier if only there had been a way to tell when the text portion of the page had finished loading without having to wait for all the images.
Actually in most cases we are primarily interested in whether a particular element in the page has loaded yet so that we can reference it. The simple solution therefore is to set up some code that will test if the element with a particular id has loaded yet and continue repeating the test at intervals until either the required element is found to be available or until the whole page completes loading (just in case an element with that id doe not in fact exist on the page at all).
First thing is to add a few lines of extra code to the top of our Javascript that will perform the necessary tests.
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);
}
The next step is to identify the id within the web page that your code is actually dependent on. If it is dependent on more than one id then choose the one closest to the bottom of the page. All we need to do to complete the process is to replace the original window.onload statement with a call to our new function. Let's assume that the id we need to have loaded is 'myid' and that the original onload statement looks like this:
We simply replace this one line with a call to our new function like this:
With that change in place the code in the start function will now be run as soon as the element in the page having an id of 'myid' is available rather than waiting for the entire page to load.
Making this small change to your code will allow the Javascript to run as soon as the necessary element in the web page is available rather than having to wait for the entire page including all of the images to load.

