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 trialKirt Perez
7,374 Pointsdocument.getElementById('roomList') returns a null. Is it wrong to use DOMContentLoaded to fix it?
Hello all, in my attempt I was trying to get the div with the id "roomList" but it was returning null. After some searching, I learned that the javascript file is being ran before the HTML is fully loaded. As a fix I implemented an event listener with DOMContentLoaded and it fixed it. Is this a bad solution?
1 Answer
Martin Balon
43,651 PointsHi Kirt, If you want to keep your script inside <head> I would suggest using keyword defer. This will run your script after DOM is loaded. https://www.w3schools.com/tags/att_script_defer.asp
<script src="js/widget.js" defer></script>
You could also move your script right above the closing body tag - the effect is the same.
I have also notice in react and vue that they put their scripts in the <head> with preload and then same scripts before closing body tag with keyword defer. I guess they preload them while html and css is rendering so they can run them immediately afterwards. Just open facebook in developer tools and see what I mean.
Kirt Perez
7,374 PointsKirt Perez
7,374 PointsHmm, if I can recall, there was some reason as to why the teacher used the script tag in the head in one of these videos. All this time I was used to putting at the end of the closing body tag but seeing that this is a solution, I feel like I should just stick to that way fully.