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

Viewed 2004

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>

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.

Related