body onload and [removed] at the same time

2019-08-28 01:50发布

问题:

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

回答1:

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.



回答2:

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>


回答3:

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>


回答4:

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);