17
Feb 09
0

Best Practices For onLoad Javascript

I recently asked a question and was pleased to receive an answer that was simple, concise, and worked perfectly.

I was asking about the best design pattern for handling several tiny, but separate scripts to run on page load. Most of these scripts were just providing focus for a specific input element. I didn’t want to write a new javascript file for each tiny chuck of onLoad code, but I also didn’t want to embed javascript directly into the HTML where it is obtrusive and easy to lose track of. An astute Stackoverflower presented me with an option that I consider to be about as perfect as it gets. Please excuse my Prototype, I am slowly working my way into the jQuery world.

Element.observe(window, 'load', function() {
    $$('.focusOnLoad').each(function(item) {
        item.focus();
    });

$$('.disableOnClick').each(function(item) {
    item.observe('click', function() {
        item.disable();
    });
});

});

Now most, if not all of my onLoad code that used to be scattered about my project, is nestled neatly into a single function, located in my project’s main javascript file. Doing this has also increased the usability of my app as before this solution, the amount of time it took to go through the painful task of writing duplicated code everywhere was great enough that not every page with an input had it auto-focusing. Now that I only have to add a single class name in each of those files, it is much easier to go through the project and make each page that much more usable.

Leave a comment

(required)

(not published) (required)