Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript AJAX Basics (retiring) jQuery and AJAX The Office Status Project Revisited

Matthew Francis
Matthew Francis
6,967 Points

Why is the javascript tag above the header here?

Aren't javascript tag supposed to be at the bottom line before the closing body tag? By putting at the top, the script needs to be downloaded first, which means it can't retrieve specific HTML ids/classes/etc. In this video, we used the jQueery method of $document.read(){} to wait for the entire document to be written.

Instead, why not just put it at the bottom?

1 Answer

In certain cases your external JavaScript file would need to be at the top of the HTML document, particularly if you wanted to alter or control in some way the CSS and HTML at page load. Obviously in a case like this, the JavaScript would have to load before the HTML for the JS to control some aspect of it. But if you're controlling the contents of your page at some point after the page has loaded, like in the case of event handling, then it is fine to have the JavaScript file loaded at the bottom of the page.

To make this a little more clear, consider it this way. If all your styling were done with JavaScript instead of CSS, then your JS would have to be at the top of the HTML or else all the HTML would present to the user as unstyled. On the other hand, if you're adding .on(func() {}) event handlers to buttons or links, it's fine for the script tag to be placed at the bottom.

I'm not an expert though. Maybe someone will be able to give more insight into this. But hopefully my explanation helped a bit!