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 trialA X
12,842 Points"Always put your script tag(s) at the end of the HTML file to ensure it loads quickly"...Why do we do this?
Hi all, I'm taking Joy's MASH track, and she mentions that you always put your script tag(s) at the end of the HTML file to ensure it (the page? or the JavaScript? or both?) loads quickly. I'm curious about why this is the case. My broader question is what order is the code executed in our HTML file? I assume it's probably not something as simple as the computer starts at the top of the file and works its way down to the bottom. Or is it? Or put another way, is the CSS, HTML, and JavaScript all read at once and executed at once, or is there a sequence to it, and why or why not?
Also, if we decided to put our script tags elsewhere, besides going against convention (like other programmers I'm sure wouldn't be happy needing to hunt through your code to find the script tag(s)), how does this negatively impact the web page you're producing?
3 Answers
Luke Buśk
21,598 PointsI believe if You place script tags at the bottom, JS can launch the code as it assumes the document object is ready (whole html code loaded up). Im not 100% sure if it works same for JS but in jQuery if You place script tags at the top, You need to add a line of code that will check if document has loaded up yet or not (document.ready()).
In short it goes from top to bottom, hence if script tags are at the bottom, JS assumes document tree (whole HTML code) is loaded up and ready.
sldknflskdngd
9,985 PointsHere is what I think and I can be totally wrong. JS is what is happening on the background of a website, as compare to HTML is 100% visual. Because we do not want the user to stare at a blank page while it loads up the JS(Which is much more complex than CSS or HTML like Joy said) we put the JS script tag at the end. After all the JS will be called once the user has something to interact with.
Omar Alladina
3,495 PointsHere is a good stackoverflow post http://stackoverflow.com/questions/436411/where-is-the-best-place-to-put-script-tags-in-html-markup
A X
12,842 PointsOmar, I don't find that StackOverflow is written for beginners, and your link is no exception.