JS: Execute JavaScript on Page Load
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:
-
function WindowOnload(f)
-
{
-
var prev=window.onload;
-
window.onload=function(){ if(prev)prev(); f(); }
-
}
I save this function in a file called init.js which is then included in my HTML pages using:
-
<script xsrc="/js/init.js" type="text/javascript"></script>
Functions can then be initialised by including the following in the HTML:
-
<script language="JavaScript">
-
<!--
-
-
WindowOnload(function()
-
{
-
a_function('Sdelete_date');
-
});
-
-
WindowOnload(function()
-
{
-
another_function('a_parameter');
-
});
-
-
//-->
-
</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 |