Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics Programming AJAX Parsing JSON Data

Joseph Michelini
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Joseph Michelini
Python Development Techdegree Graduate 18,692 Points

Is there a reason the script tag is added to the document head in this video?

I just wanted to make sure there wasn't a different set of rules regarding script tags and AJAX requests. In theory, shouldn't this script tag be added right before the closing body tag?

Thanks!

2 Answers

Steven Parker
Steven Parker
231,248 Points

This particular script starts an asynchronous process that will almost certainly take longer to complete than the page loading, but I agree that since it does eventually manipulate the DOM it should probably be loaded at the end of the page body.

Loading it in the head is probably intended to give it a "head start" (pun intentional :wink:) in attempt to reduce the delay in presenting the data on the page.

Steven Parker
Steven Parker
231,248 Points

If a script contains only library code and does not immediately interact with the HTML, it is safe (and common) to include it in the <head> section.

But any script that does any DOM interaction should be placed last in the <body>, to be sure the rest of the page has loaded before it starts.

Joseph Michelini
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Joseph Michelini
Python Development Techdegree Graduate 18,692 Points

Thank you Steven! Forgive me since I'm so new to server requests, but doesn't this request eventually interact with the DOM? Doesn't it insert HTML?

If so, what difference should I look out for between this and the kind of DOM interaction you're referring to?

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    var employees = JSON.parse(xhr.responseText);
    var statusHTML = '<ul class="bulleted">';
    for (var i = 0; i < employees.length; i += 1) {
      if (employees[i].inoffice === true) {
        statusHTML += '<li class="in">';
      } else {
        statusHTML += '<li class="out">';
      }
      statusHTML += employees[i].name;
      statusHTML += "</li>";
    }
    statusHTML += "</ul>";
    document.getElementById("employeeList").innerHTML = statusHTML;
  }
};
xhr.open("GET", "../video6/data/employees.json");
xhr.send();