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 Programming AJAX AJAX Callbacks

Why is this script element not at the end of the body tag?

I noticed that the code Dave is writing has the script element outside the body. Does anybody know the reason for that? We have learned that best practice for placing the JS code is at the end of the body tag. And I have even experienced issues if with my code when I didn't follow this advice. This is why I was wondering about his positioning.

<head>
  <meta charset="utf-8">
  <link href='//fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="css/main.css">
  <title>AJAX with JavaScript</title>
  <script>
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        document.getElementById('ajax').innerHTML = xhr.responseText;      
      }
    };
    xhr.open('GET', 'sidebar.html');
    function sendAJAX() {
      xhr.send();
      document.getElementById('load').style.display = 'none';
    }

  </script>
</head>
<body>
  <div class="grid-container centered">
    <div class="grid-100">
      <div class="contained">
        <div class="grid-100">
          <div class="heading">
            <h1>Bring on the AJAX</h1>
            <button id="load" onclick="sendAJAX()">Bring it to me!</button>
          </div>
          <div id="ajax">

          </div>
        </div>
      </div>
    </div>
  </div>
</body>

2 Answers

Steven Parker
Steven Parker
220,426 Points

Scripts that only load libraries, define functions, or establish data resources can be safely loaded in the "head" section of the page, and it is a common practice to do so.

But any script that interacts with the DOM should always be loaded as the last thing in the "body" section, and as you have seen can create errors if it is loaded before the page elements that it references.

This script is an example of the first kind since it defines functions that don't run until the page button is clicked.

Thank you Steven! I got confused for a second there. Sometimes I feel that I don't have full knowledge of where it's best to place some lines of code. But your explanation makes a lot of sense.