JavaScript JavaScript and the DOM 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

Juthawong Naisanguansee
Juthawong Naisanguansee
Full Stack JavaScript Techdegree Graduate 79,754 Points

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