Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 253
Prabhavith Avatar asked Oct 31 '25 14:10

Prabhavith


1 Answers

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();
       }
    }());
    
like image 156
Fabrizio Calderan Avatar answered Nov 02 '25 05:11

Fabrizio Calderan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!