Method 1:
<script language="javascript">
function init(){
...code...
}
window.onload=init;
</script>
Basically, you define the function and then assign that function name to the event handler. You'll notice that the parenthesis () were left off the end of the function name, this is intended. Adding the parenthesis will cause the function name to be assigned to the event instead of executing it; not really what you want I don't think.
Just copy all the script and it automagically causes the function called init() to run only once the page is finished loading! |
Method 2: Instead of calling a predefined function with the window.onload event handler, you can also assign a "nameless" function directly like this:
<script language="javascript">
window.onload=function(){
...code...
}
</script>
In this example, you don't predefine a named function, you just assign the function body to the event.
|
Method 3: Or, you can use the Function() contructor like in this example:
<script language="javascript">
window.onload=new Function("...code...");
</script>
This last one is a little more difficult to use since all commands must be in string form. This can cause problems if you need to use other quotes in the command list; you have to escape them or use single quotes. Plus it isn't quite as easy to see what is going on unless the command string is short and simple. I don't use this version very often for this reason. I usually use either of the first 2 ways.
|
Script #1:
<script language="javascript">
function start(){
...code for script #1...
}
window.onload=start;
</script>
|
Script #2:
<script language="javascript">
function init(){
...code for script #2...
}
window.onload=init;
</script>
|
Result:<script language="javascript"> function start(){ ...code for script #1... } function init(){ ...code for script #2... } window.onload=function(){ start(); init(); } </script> |
Script #1:
<script language="javascript">
function start(){
...code for script #1...
}
window.onload=start;
</script>
|
Script #2:
<script language="javascript">
function init(){
...code for script #2...
}
window.onload=init;
</script>
|
Result:<script language="javascript"> function start(){ ...code for script #1... } function init(){ ...code for script #2... } function initAll(){ start(); init(); } window.onload=initAll; </script> |
Script #1:
<script language="javascript">
function start(){
...code for script #1...
}
</script>
<body onload="start()">
|
Script #2:
<script language="javascript">
function init(){
...code for script #2...
}
window.onload=init;
</script>
|
Result: Notice how I removed the event from the BODY tag and put it into the script. <script language="javascript"> function start(){ ...code for script #1... } function init(){ ...code for script #2... } window.onload=function(){ start(); init(); } </script> <body> |