javascript - what's the difference between onload action and an action in a bottom script -


is there functional difference between using body onload:

<!doctype html> <html> <head>     <title>testing body onload</title> </head> <body onload="fu('this body onload')">     <h2 id="i1">nothing yet</h2>     <script>         function fu (msg) {             document.getelementbyid("i1").innerhtml = msg ;         }     </script> </body> </html> 

on 1 hand , executing script @ end of 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 bottom script') ;     </script> </body> </html> 

the second seems better me, when there more actions when page loaded. maybe there pitfall don't know?

yes, there is. putting code @ bottom putting in domready event, not onload.

domready means html code read (so dom ready, or in other words, can find dom elements js selectors), while onload means assets (img, css, etc..) loaded (so, longer event).

edit:

please refer mdn docs:

(this jquery's domready, , it's document object's event): https://developer.mozilla.org/en-us/docs/web/events/domcontentloaded

this onload event, , it's window object's event: https://developer.mozilla.org/en-us/docs/web/api/globaleventhandlers/onload


Comments