loading more than one javascript when page loads

They have: 426 posts

Joined: Feb 2005

I am writing some javascript that uses the window.onload to load a function when the page loads.

This script will be used / included by different websites and i have no idea if they are already using window.onload; if they are then it will overide my own window.onload.

How can i load my scripts when the page loads and not interfer with other scripts loading when the page loads?

decibel.places's picture

He has: 1,494 posts

Joined: Jun 2008

I think if you place a script in the body that has onload=init; and in the init() function you then load the required functions that should work... but it could supercede an onload= in the body tag.

If that interferes, then you could try just placing the init() function call at the end of the page, but it might fire off early (before page is fully loaded - which might not matter) - in the attached file it is after the body but before the closing html tag.

here is a discussion of triggering onload when the DOM has loaded

He has: 629 posts

Joined: May 2007

... and if you are just looking to do stuff after the page is loaded, here is a simple solution: Executing JavaScript on Page Load.

JeevesBond's picture

He has: 3,956 posts

Joined: Jun 2002

I know this doesn't directly answer your question (think the other two solutions posted above do that perfectly), but many JavaScript developers are using JQuery these days. It makes stuff like this very easy.

$(document).ready(function() {
  // Do stuff when the document is loaded.
  alert("Hello world!");
});

a Padded Cell our articles site!

decibel.places's picture

He has: 1,494 posts

Joined: Jun 2008

JeevesBond wrote:
many JavaScript developers are using JQuery these days. It makes stuff like this very easy.

I usually avoid using frameworks like Jquery and Prototype because they add a lot of code that is not ever used (I know many Drupal modules depend on Jquery).

This looks like a good reason to use Jquery - or maybe just extract the part relevant to $(document).ready

They have: 426 posts

Joined: Feb 2005

Hi Jeeves,

Yes i am using jquery already, but doesnt the $(document).ready not overide the onload event?

This does sound reasonable if it does not.

However as from the link that has been provided above, this is also a reasonable solution to add my function to the window.onload if something already exists, but if the onload has been run from the tag this probably will not work?

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.