Creating Dynamic "onload" Events Using JavaScript

Posted by Dan on Jun 18, 2003 @ 9:49 AM

I posted a new article to PengoWorks.com today that shows a technique for running multiple onload events without altering your base source code. Here's a quote:

One of the most common things I run into while developing sites dependant on JavaScript is the need to have multiple operations run during <body>'s onload event. I think this is a problem most developers run into, since it's very common to develop a set of "shared border" templates that render the shell of your site and the body of your document is included via a server-side command.

Often you have the need to invoke some JavaScript during the onload event of every page. This might be to render a DHTML-based menu, or simply to initial some information about the page, regardless, you need this information to run on every page.

However, you often run into the case were you need to run some addition commands based upon the page that's being inserted. Most often this happens when I'm developing a page that has a form on it. There are a lot of ways to tackle this problem, but the tip I'm going to share with you is the one that I've found over the years to be the best solution. For a lack of a better term, I'll call this the "Auto-init()" method.

If you have any comments about the article, please post a comment!

Categories: JavaScript, HTML/ColdFusion, Source Code

2 Comments

  • Interesting technique. I particularly like the array of functions approach. I guess what a lot of developers do (i.e. me) is use something like body onload="#request.bodyOnload#" where the body of the page just appends items to this list. This of course only works where you generate the entire page before outputting anything, but this is a common technique, e.g. in Fusebox.

    Do you think your technique offers any advantages over this technique for Fusebox users?
  • Matthew,

    That's the technique I *used* to use. I find it's pretty kludgy though. It also means you have to process the template to ensure that all actions get performed before invoking your header tag. That's not a huge deal in Fusebox, but passing it in a string always seem kludgy me.

    My method also allows saves server-side processing, since the check to see if a function needs to run is handled by the client. As far as the server goes, it either outputs a matching function or not. The processing hit to the client is pretty much nil, but it saves your server a wee bit of work.

    I've done it both ways and really prefer this method--it just makes more since to me.

    -Dan

Comments for this entry have been disabled.