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 ${} to wait for the entire document to be written.

Instead, why not just put it at the bottom?

1 Answer

Michael Cook
Michael Cook
Full Stack JavaScript Techdegree Student 24,407 Points

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!