Where do I put the links to my Javascript/jQuery files in my html file?

I recently noticed that some (not all) of my javascript and jQuery scripts wouldn't work unless I put the link for the .js files nearer towards the bottom of the page instead of the head area where I put my links for my .css files.

From what I understand, javascript can go in either places and it is recommended to not be put in the header as it slows down the page loading process as well. At the same time, if I put it in the body tag of the html file, it looks somewhat messy and was wondering what the best practice is for putting .js files in a cleanly place. Should I always put it at the very bottom right before the ending body tag? How do professional web developers handle this?

Answers:

Answer

If your scripts did not work unless you put them towards the bottom then you most probably started manipulating the DOM when the DOM wasn't ready yet (or maybe you used document.write, but I doubt that this was the case). To solve this you need to start processing only when the DOM is ready. With jQuery you'll need something like:

$(function() {
    // DOM is ready here and you can safely manipulate it
});

Regarding how the positioning of the scripts affects performance I suggest you read those 3 articles from the guru of client side performance:

Asynchronous loading and delayed execution are very hot subjects right now. They allow you to cleanly define everything at the <head> but be very specific about how they get loaded and when they are excecuted.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.