Search code examples
jqueryheaderfooter

Should Jquery code go in header or footer?


Where is the best place to put Jquery code (or separate Jquery file)? Will pages load faster if I put it in the footer?


Solution

  • All scripts should be loaded last

    In just about every case, it's best to place all your script references at the end of the page, just before </body>.

    If you are unable to do so due to templating issues and whatnot, decorate your script tags with the defer attribute so that the browser knows to download your scripts after the HTML has been downloaded:

    <script src="my.js" type="text/javascript" defer="defer"></script>
    

    Edge cases

    There are some edge cases, however, where you may experience page flickering or other artifacts during page load which can usually be solved by simply placing your jQuery script references in the <head> tag without the defer attribute. These cases include jQuery UI and other addons such as jCarousel or Treeview which modify the DOM as part of their functionality.


    Further caveats

    There are some libraries that must be loaded before the DOM or CSS, such as polyfills. Modernizr is one such library that must be placed in the head tag.