Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialmatthewshear
9,229 PointsWhy are you saying its best practive to put JS files in the body?
I was always taught best practices were to keep all links to JavaScript files in the header. or the page If I went on an interview, did a coding test and put JS files in the body of the page, I would expect them to laugh at me. When did this go from totally unacceptable to common practice? This just seems wrong.
1 Answer
Kevin Korte
28,149 PointsIt's really to avoid littering your your js files with a bunch of $('document').ready(function({});
, because there are many instances where you don't want that javascript to fire until after the dom has been loaded. Keeping your code inside of the ready function on the document is one way, another is to put those javascript files last in the dom, since the dom will be loaded from top to bottom, if the js files are last, you can be pretty sure that whatever dom element they're going to attach to is already loaded.
Obviously loading the js files last will keep files sizes just slightly smaller thanks to a few less lines of code here and there. Pick your poison.
Joel Bardsley
31,249 PointsJoel Bardsley
31,249 PointsTo add to this, there is a performance factor as scripts are 'blocking' resources - in other words, when the browser encounters a script tag, it blocks further rendering of the page until it has fetched and executed the script. So if scripts are located in the head, the visitor would see a blank white page until the scripts have loaded, and then the body content would appear. Having them at the bottom allows the html and css to load first, giving the visitor the perception that the site has loaded faster.
Nick Pettit explains in further detail here: Optimize JavaScript | Front End Performance Optimization