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

Dontre Waggoner
Dontre Waggoner
9,282 Points

Why doesn't my code work when I link the script src in linked in the head tag?

Hi there,

I was having troubles with my code running because I linked my javascript in my head and not before the closing body tag. I normally do this in most cases but I'm learning that's not always the best practice.

Can I have someone explain what prevented it from working? And to also help with explaining when I should link in the head and when I should link to the body tag , for future reference?

1 Answer

Hi Dontre,

When the browser is parsing the HTML and encounters a script tag, it stops parsing the HTML in order to execute the JavaScript.

So if you have code in your script file that manipulates the DOM, then the JavaScript interpreter may throw errors if the nodes you’re asking it to manipulate haven’t been constructed yet.

For instance, if your external js has code that adds an event listener to a div, but the div in question hasn’t been constructed by the browser, then the interpreter will assume you’re trying to attach an addEventListener function to an undefined element. It won’t understand how to reconcile that, and so it’ll stop executing the rest of the JavaScript.

But if you include your js near the closing body tag, then all of the DOM nodes will have been constructed before the script is loaded and executed.

The other reason you might include js near the end of your HTML is so your client isn’t forced to wait for a bunch of script files to be requested, loaded, and executed before they have a chance of seeing anything displayed on the page (because like I mentioned, the blocking nature of JavaScript means that the browser pauses DOM construction when it encounters a script tag).

I’m still learning all the intricacies of the front end so I haven’t had to include js in the head of my documents yet, but I imagine there are scenarios where perhaps you want to use javascript to inform how the browser should interpret the html it will parse (and so you include it in the head because you want the construction of the DOM to be blocked). But that’s only speculation on my part.