Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Macman1993

macrumors 6502
Original poster
Nov 23, 2007
337
16
Ok so I'm working on a script and one of the requirements of it is a function occurring when the page loads. I know I can edit the body tag to do this easily but I want to know if there is a way to do this without editing the body tag. I know this is a bit odd but my reason for this is for example if I wanted to use this script somewhere I didn't have access to the body tag i.e. a forum and I wanted to use this script as a footer. Does anyone know a way I can do this.

I just found out that I can add a second body tag later in the page that includes the onload that I need. I figured this would be a very bad way of doing things, is that a perfectly fine way to do this or is this going to cause problems with other browsers?
 
window.onload = function() { ... }

Two body tags is invalid.

Also, be aware that the above will replace any previously existing onload handler.

If you use jQuery, you can define as many ready handlers as you want:

$(function() { ... });
 
Two ways:

The first is that mentioned by bootedbear -

window.onload=function(){yourFirstFunctio(); yourSecondFunction();}

The second is to use the following function - I think I got it from a Sitepoint book but could be wrong ...

Code:
function addEvent(elm, evType, fn, useCapture)
{
   if(elm.addEventListener)
   {
      elm.addEventListener(evType, fn, useCapture);
      return true;
   }
   else if(elm.attachEvent)
   {
      return elm.attachEvent('on' + evType, fn);
   }
   else
   {
      elm['on' + evType] = fn;
   }
}

Then use it like

Code:
addEvent(window, 'load', yourFirstFunction, false);
addEvent(window, 'load', yourSecondFunction, false);

You just put the last two lines at the bottom of the script file containing your functions then whenever you include that script in a page the functions will run on load.
 
Not sure if it's out of your scope/requirements, etc.. but jQuery is amazing

You can even load functions once the dom is loaded (ie. before the entire page is downloaded/rendered).

It's also extremely simple to learn (relatively of course)

Of course this has some overhead since you'll need to use the relative parts of the jQuery library, so if it's just a simple function you're looking for than maybe the solutions mentioned are better. Nevertheless I definitely recommend at least taking a look at jQuery =). Saved me countless hours.

$(document).ready(function(){
...

});
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.