Search code examples
javascriptdom-eventsonload

Difference between Javascript onload event and plain script in the html page


What is the difference between these two pieces of code:

Sample 1:

<script type="text/javascript">
     function myfunc () {
                alert('hi');
            }
         window.onload = myfunc;
</script>   

Sample 2:

<script type="text/javascript">
     alert('hi');//no function used 
</script>

Both pieces of code execute successfully.


Solution

  • The window.onload makes it so that all DOM elements are loaded before the script runs - that is, if your script modifies or uses DOM elements, then it should be attached to window.onload (or something equivalent in a framework). If it is independent of the DOM you can use either. Refer to the Mozilla Developer Network page for more information. Note that inlined scripts that don't run from window.onload can run once the parser reaches it - it doesn't wait for the rest of the DOM to be loaded.