Prabhavith
Prabhavith

Reputation: 486

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.

Upvotes: 4

Views: 6396

Answers (3)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

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();
       }
    }());
    

Upvotes: 4

thomthom
thomthom

Reputation: 2914

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.

Upvotes: 1

Robin Whittleton
Robin Whittleton

Reputation: 6339

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 (e.g. $(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.

Upvotes: 2

Related Questions