Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should JS scripts go in an HTML file?

If you have JS code which is intended to run as part of loading/building the page, where in the HTML should this go? For instance modifying a <div> or adding some links. Should this be put in the <body>, interspersed with HTML? Or should it be between the <head> and <body> elements? What order do things happen in - the order they are in the page or does HTML all happen before (non-<head>) JS is run?

like image 397
Mr. Boy Avatar asked Mar 07 '11 13:03

Mr. Boy


People also ask

Can JS scripts be put anywhere in an HTML file?

There is a flexibility given to include JavaScript code anywhere in an HTML document. Javascript code can be embedded in: The header of the page in between 'head' tags. Body of the page in between 'body' tags.

Where should JavaScript files go?

For best performance place your JavaScript files at the BOTTOM of the HTML page you are serving. To ensure that everything is set when you try to use it, execute only after the DOM is ready (there are multiple variations of this, my advice: Use a JavaScript Library).


3 Answers

If you have JS code which is intended to run as part of loading/building the page, where in the HTML should this go?

Just before the closing </body> tag is emerging as the best practice barring a specific requirement for it to be elsewhere (which there can sometimes be). It's the recommendation of the YUI folks, for instance, but it's not just them.

What order do things happen in - the order they are in the page or does HTML all happen before (non-) JS is run?

When a script tag is encountered, unless you use the defer or async attribute (and the browser supports them), all HTML parsing comes to a screeching halt and the script is downloaded and handed to the JavaScript interpreter. When the JavaScript interpreter finishes processing the script, the HTML parser can continue. It has to do this because the JavaScript can insert tokens into the HTML stream via document.write. This is also why you can load a script file and then load a second script file that relies on the first, and know that they'll get loaded in the right order. It's also why you can't access elements that are further down in the HTML stream from a script higher up in it unless you defer your code somehow (window.onload or the "DOM loaded" events many libraries support, such as jQuery's ready or Prototype's dom:loaded).

An upshot of this is that the typical practice of putting script tags in the head actually slows down the apparent load time of the page, unless those script tags need to be there for some reason. Hence the recommendation to put them just before the closing </body> tag.

There's a "gotcha" you have to watch for, though: If you have parts of the page that you want to respond to with JavaScript if the user has it enabled, loading your script at the very end leaves a brief but real race condition lying around: The user can interact with the page while your script is being downloaded. There are a variety of ways of handling that. My favorite is to detect whether JavaScript is enabled with inline script (not a separate file) in the head element and, if so, to put in a document-level handler for things where possible (you can do this with click events, for instance) which basically queues up or disables the click during that very brief period of time. That way, if JavaScript is enabled, you'll avoid the race condition, but if it isn't, any unobtrusive fallback you have in place will work.

like image 99
T.J. Crowder Avatar answered Sep 24 '22 00:09

T.J. Crowder


The whole HTML file is executed in the order it is written, that means

<html>
  <div id="ID"></div>
  <script type="text/javascript">
    document.getElementById('ID').innerHTML = "HELLO";
  </script>
</html>

changes the contents of the div, wherease

<html>
  <script type="text/javascript">
    document.getElementById('ID').innerHTML = "HELLO";
  </script>
  <div id="ID"></div>
</html>

does not, because the JS code is executed before the div has loaded.

EDIT: If you want the JS to run after the page has loaded use window.onload or document.body.onload or

<body onload="...">

Alternatively if you're using a JS library such as jQuery, you can use

$(document).ready(function() {
  ...
});
like image 21
hennes Avatar answered Sep 22 '22 00:09

hennes


Put them as functions in its own .js file which you include by <script src> at end of HTML <head> or <body>. If any of them needs to be executed during document load, call it using window.onload or whatever load function the JS library/framework offers, if you are using any.

As to the exact location, putting them in end of <head> allows them to be downloaded before the HTML page is been shown in browser and putting them in end of <body> allows the page to be shown a tad sooner because downloading the scripts will block the page rendering, thus it's a better speed experience.

However, IMO, it's a bit more robust to have the scripts downloaded before the page is rendered whenever you have some page elements which cannot be used without JS. In case of an impatient user this would otherwise lead to unusable elements.

like image 45
BalusC Avatar answered Sep 24 '22 00:09

BalusC