What is the difference between the onload action and the action at the bottom of the script

Is there any functional difference between using a load on the body:

<!DOCTYPE html>
<html>
<head>
    <title>testing body onload</title>
</head>
<body onload="fu('this is from body onload')">
    <h2 id="I1">nothing yet</h2>
    <script>
        function fu (msg) {
            document.getElementById("I1").innerHTML = msg ;
        }
    </script>
</body>
</html>

on the one hand, and the execution of the script at the end of the body:

<!DOCTYPE html>
<html>
<head>
    <title>testing body onload</title>
</head>
<body>
    <h2 id="I1">nothing yet</h2>
    <script>
        function fu (msg){
            document.getElementById("I1").innerHTML = msg ;
        }
        fu('this is from bottom script') ;
    </script>
</body>
</html>

The second seems to me better, of course, when there are more actions that you need to do when loading the page. But maybe there is a mistake that I don’t know about?

+4
source share
2 answers

Yes there is. Putting your code at the bottom is like including it in a domready event, rather than onload.

Domready means that the html code has been read (so dom is ready, or in other words, now you can find the dom elements with js selectors), and onload means that all assets (img, css, etc.) are also loaded ( so, a much longer event).

Edit:

MDN:

( jquery domready, ): https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

onload, window: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

+7

onload Mozilla:

. , DOM, , , .

, HTML.

onload, .

+4
source

Source: https://habr.com/ru/post/1598180/


All Articles