body onload and window.onload at the same time

Can I use body onload and window.onload at the same time? I've tried it using this code

<body onload = "alertFirst()">
</body>
<script>
    window.onload = alertSec;
</script>

But it didn't work. I just need someone to confirm it to me. Many thanks

Answers:

Answer

If one or more of the scripts you want to use has the event handler in the BODY HTML tag, you can still move it to into javascript code. See the example below:

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:

<script language="javascript">

function start(){
...code for script #1...
}

function init(){
...code for script #2...
}

window.onload=function(){
start();
init();
}

</script>

<body>

I think it may can help you.

Answer

The answer to your question is "no". However there are ways around it.

Adding both calls to one onload function is ideal, but if you /have/ to add an onload handler after one is already added, and you are not using a framework which facilitates this, you can get by like this:

<html>
    <head>
        <script type="text/javascript">
            function alertFirst(){
                alert('First');
            }
            function alertSec(){
                alert('Second');
            }
        </script>
    </head>
    <body onload="alertFirst();">
        content
    </body>
    <script>
        var func = document.body.onload;
        window.onload=function(){
            func();
            alertSec();
        }
    </script>
</html>
Answer

You can (by adding event handler(s)) but you should NOT have both

Instead add the call to the window.onload:

<html>
<head>
<script>
  window.onload = function() {
    alertFirst();
    alertSec();
  }
</script>
</head>

<body>
</body>
Answer

No, document.body.onload is actually mapped to window.onload. You can check yourself—when you have <body onload="a()"> and to console.log(window.onload), a() is printed out into the console.

What you can do is to have one onload event handler that calls two other functions.

window.onload = function () {
  a();
  b();
};

or two event listeners

window.addEventListener('load', a, false);
window.addEventListener('load', b, false);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.