简体   繁体   中英

Position of window.onload in Javascript

I have a javascript code like this

<script type="text/javascript">
window.onload=myFunction;
</script>

Is there any difference in using the above snippet in the <head></head> tag and just before </body> tag, as I would like to call my function after the page loads.

basically there's no pratical difference, but I recommend

  1. to place that code at the bottom, since you need to use a script (blocking-rendering tag) it's better put it at the end of the document.

  2. to avoid a destructive assignments like that: writing window.onload=myFunction you destroy other previous assignments to window.onload event (if any) so it's better something like

     (function() { var previousOnLoadIfAny = window.onload; window.onload = function() { if (typeof previousOnLoadIfAny === 'function') { previousOnLoadIfAny(); } yourfunction(); } }()); 

Binding to window.onload will always run your function when the load event fires. This only fires after everything in the page has finished loading, including images etc. If you want to run your function when the DOM has finished loading but before everything else then you can bind to the DOMContentLoaded event or use a library like jQuery (eg $(function(){ myFunction() }); ).

The benefit about putting your function at the end of your <body> is that theoretically this means that the rest of your content has already loaded and you don't need to bind your function to a load event. This sometimes works, but depends on the situation.

No, where you place that will not matter - anywhere in the document and it will trigger when the document and all external resources (images, scripts etc) has loaded.

Because onload triggers after all external resources one often want to use DOMContentLoaded instead which triggers when the HTML DOM is ready. Which will make for a page that is more responsive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM