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 trialJoseph Michelini
Python Development Techdegree Graduate 18,692 PointsIs 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
231,275 PointsThis 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 ) in attempt to reduce the delay in presenting the data on the page.
Steven Parker
231,275 PointsIf 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
Python Development Techdegree Graduate 18,692 PointsThank 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();
Joseph Michelini
Python Development Techdegree Graduate 18,692 PointsJoseph Michelini
Python Development Techdegree Graduate 18,692 PointsThank you Steven! That's great and makes a ton of sense.