1

I understand inline javascripts scattered through html code like the following example is bad

<html>
  <head>
  </head>
  <body>
     <p> Foo <script></script></p>
  </body>
</html>

However, after coding for a while, understanding that loading Javascripts at the end of the document is the best way to go. I do see a lot of the sites that conform to loading scripts at the end of their document, do so in the following manner :

<html>
  <head>
  </head>
  <body>
     <p> Foo </p>
     <script></script>
  </body>
</html>

What is not made clear, is why not :

<html>
  <head>
  </head>
  <body>
     <p> Foo </p>
  </body>
  <script></script>
</html>

.. as this is outside the body tag which means that the body (in theory) can process faster and still load your scripts before finalizing on </html>.

Or even this :

<html>
  <head>
  </head>
  <body>
     <p> Foo </p>
  </body>
</html>
<script></script>

Each variation will have (in theory) different performance results, and/or may break functionality in the page depending on the script contents of course.

Of the above formats, which one is the ideal place to load javascripts that would have the highest performance gain without breaking html ?

Kraang Prime
  • 9,981
  • 10
  • 58
  • 124
  • @AndrewL. - async defer only refers to downloadable scripts, not inline javascript. It also mucks up the order. – Kraang Prime Sep 04 '16 at 01:09
  • You're correct, let me retract the duplicate flag. – Andrew Li Sep 04 '16 at 01:10
  • My understanding is that any script elements located AFTER the closing body tag are acted upon as if they were in the head portion. Ie - before the body portion rendered. Could be wrong. Before the closing tags is best in terms of page performance - unless of course the js is required directly for the rendering of elements in the body. – gavgrif Sep 04 '16 at 01:19
  • 1
    I do see a lot of wordpress sites that load all the plugins and dependant js in the head - can make for a VERY SLOW loading wp site. – gavgrif Sep 04 '16 at 01:26

7 Answers7

2

The best place at the end of the body tag, like

<html>
<head>
</head>
<body>
some html body tags
.
.
.
<script> external or inline </script>
</body>
</html>

If you do like so, then the html will load quicker and main pros is that all your ids and classes will get assigned otherwise sometime if you put script above html, then there might be a chance that you try to get an element by id that is not yet assigned in DOM

[UPDATE]

Here is an example code that Bootstrap is using in their own website: http://getbootstrap.com/getting-started/

you can find this code under Basic template Heading:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <h1>Hello, world!</h1>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>
Irfan Anwar
  • 1,878
  • 17
  • 30
2

How browsers work: As you can see from here, most of the browsers parsing the html elements top to bottom in elements tree hieararchy.

So, when you put a script just before </body> tag, make sures that most of the elements has been loaded or at least parsed. Or, you just need to wait for document.readyState.

Also, by putting your script below </body> tag is semantically not good. But, you can do it and it won't make a difference for the performance.

Inanc Gumus
  • 25,195
  • 9
  • 85
  • 101
2

As noted here, the script tag won't validate outside of the body or head tags. However, you want to place it as far down as possible, so that the rest of the page loads first, to avoid errors. This leaves us with the place furthest down, but inside the body and head tags: just before the closing body tag.

<html>
  <head>
  </head>
  <body>
     <p> Foo </p>
     <script></script>
  </body>
</html>
Community
  • 1
  • 1
Feathercrown
  • 2,547
  • 1
  • 16
  • 30
2

If you know how the browsers work it will be easy to know where to put it. First of all it's invalid to include your script after the body or the html element. Only comments and the closing tag for html are allowed after the body. Some browser will do recovery but you shouldn't depend on that.

You may include it any where in the body or the head but you should know that script take the browser attention may be for while and I will stop rendering the dom. That's very bad for user experience so the best place to include it just at the end of the body element.

Like in the example :

<html>
  <head>
  </head>
  <body>
     <p> Foo </p>

     <!-- ...  -->


     <script></script>
  </body>
</html>

One more thing if you include the script at the top of the page and that script will manipulate the dom that may cause an error if the dom isn't ready yet. The script searching for element which is not exist yet. And it will be very confusing when it runs at time and it doesn't run in another time. You may check the answers for similar questions here and here

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • *"that may cause an error if the dom isn't ready yet"* - Except that if you *did* put your script in the head then you'd use a `DOMContentLoaded` handler to guarantee that scripts that manipulate the DOM run after the DOM is ready, so you wouldn't get errors. (Not that I'm saying putting it in the head is best, but there is no issue with errors if you code it properly.) – nnnnnn Sep 04 '16 at 01:39
  • totally agree with you. That's exactly what is the ready function do in the iQuery. I think the computers and the internet connections are fast enough to load the script without the user feel any blocking. Also there's async property that tell the browser to hand it the script asynchronous so it wouldn't cause any blocking – Abdelrhman Hussien Sep 04 '16 at 01:50
1

Important thing to note is the following:

If you put the script in the head tag HTML page rendering is blocked until the script is downloaded. The more scripts you will put there the slower your page will load.

That’s why an advanced approach is to put the scripts at the bottom of the BODY, and in this case the user can start interacting with a page before the Javascript has Loaded.

You will put the scripts in HEAD only if they MUST be available before the page is shown.

Franco
  • 2,309
  • 1
  • 11
  • 18
1

Best way to load your java-script at the end of body tag, but in some case when you use third party script, it need be load before control initialize.

<html>
   <head>
   </head>
   <body>
       ...........
   <script></script>
   </body>
</html>
1

JavaScript is a render blocking resource. So when browser is parsing HTML document and encounters script in between, the control is passed to js engine. Which runs the script and returns the control to browser again.

 <html>
   <head>
      <script src="/main.js" />
    </head>
   <body>
    <script>
              //some inline script
    </script>
   </body>
</html>

So when broswer encounters the script tag in header, it passes the control to js engine. Now beacuse the script is being loaded from network, js engine will wait for script to load. After that it will be executed. Then document parsing will resume. (Inline script in head would have worked faster as network delay would be avoided)

Same goes for inline script. Situation gets complex if CSS is also present along with javascript. If a CSS is also being loaded from network in the head, js engines will wait for it too. So there are 2 dependencies now.

So it is best to add js at the bottom and CSS at top generally (to avoid Flash of Unstyled Content).

A good read for the same is present here : Critical Rendering Path