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 JavaScript and the DOM (Retiring) Getting a Handle on the DOM A Simple Example

linking javascript to html

why we are not linking our javascript in head tag just like other scripts?

2 Answers

Hello Apoorv ,

There are many Reason Most Web Developer don't include Javascript in head tags. For Example when the browser execute javascript too early before the select DOM Element not load yet. It will throw an exception and breaking the javascript execution causing big mess.

However , We make a getaway using Event Listener that wait until page fully loaded like this

document.getEventListener('DOMContentLoaded',function(){
 document.getElementById('juthawong').innerHTML = "Test";
});

Moreover , I read some article on the internet that Javascript is block rendering.So that page render slower. So We Rather Use Async Tag To Prevent Block Rendering or Put it on the Body after those html element are loaded.

References :

https://stackoverflow.com/questions/14328449/when-do-you-put-javascript-in-body-when-in-head-and-when-use-doc-load

https://www.upwork.com/hiring/development/11-tips-to-optimize-javascript-and-improve-website-loading-speeds/

Thank you

thank you very much for your time and answer.

Go back through and listen to the video where he goes over where JS goes.

https://teamtreehouse.com/library/javascript-basics/introducing-javascript/where-does-javascript-go

It all comes down to speed really. Have the content load before making htem wait on Javascript, it's especially important when thinking about how long a page may take to load on a mobile device that isn't on 5 bars/wifi