yes i love technology

JS: Execute JavaScript on Page Load

May 14th, 2007 by Pete

Recently I’ve been making an effort to improve my JavaScript skills, I’m not a JavaScript-Jedi yet but I have been picking up a few, tips, tricks and techniques.

One thing that I find extremely useful is using an init function to call other functions when the page has loaded. I have been using the nifty function below:

JAVASCRIPT:
  1. function WindowOnload(f)
  2. {
  3. var prev=window.onload;
  4. window.onload=function(){ if(prev)prev(); f(); }
  5. }

I save this function in a file called init.js which is then included in my HTML pages using:

HTML:
  1. <script xsrc="/js/init.js" type="text/javascript"></script>

Functions can then be initialised by including the following in the HTML:

JAVASCRIPT:
  1. <script language="JavaScript">
  2. <!--
  3.  
  4. WindowOnload(function()
  5. {
  6. a_function('Sdelete_date');
  7. });
  8.  
  9. WindowOnload(function()
  10. {
  11. another_function('a_parameter');
  12. });
  13.  
  14. //-->
  15. </script>

The above code is inline JavaScript which is often seen as being naughty, obviously you can save the same code to a separate file and include that instead.

I originally saw this technique here. Alternative JS initialisation scripts are available but so far this one has worked well for me, so I’ll be sticking with it.

# Pete Graham

Posted in javascript, Website Development, programming |

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.