Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

body onload function is not working in my Example (JavaScript)

I am writing a program to find sequence of execution of document.ready, window.onload, body.onload, but due to some reason my body.onload is not giving out console.log. Why?

$(document).ready(function(){
    console.log('document is ready now ...');
});

window.onload = () => {
    console.log('window is loaded...');
}

function bodyOnload() {
    console.log('body is loaded...');
}
<html>

<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<body onload="bodyOnload()">

<h1>Hello ...</h1>

</body>

</html>
like image 285
Deadpool Avatar asked May 30 '26 15:05

Deadpool


1 Answers

I'm gonna tell you the reason with some example cases... enter image description here

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        console.log('document is ready now ...');
    });

    window.onload = () => {
        console.log('window is loaded...');
    }

    function bodyOnload() {
        console.log('body is loaded...');
    }
</script>
</head>
<body onload="bodyOnload()">
<h1>Hello ...</h1>
</body>
</html>

As you can see window.onload doesn't work in the above case. But in the below case, you can see that body.onload doesn't work.

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body onload="bodyOnload()">
<h1>Hello ...</h1>
<script>
    $(document).ready(function(){
        console.log('document is ready now ...');
    });

    window.onload = () => {
        console.log('window is loaded...');
    }

    function bodyOnload() {
        console.log('body is loaded...');
    }
</script>
</body>
</html>

enter image description here

So even if you write the separately it won't wok. Overall, those can't be working together. Why? window.onload means the body is already loaded and body.onload also means the window is already loaded. since the reason, in case one of both is called the other one will be ignored.

like image 131
web-sudo Avatar answered Jun 01 '26 05:06

web-sudo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!