I often see some JavaScript libraries that are called in the head tag of an html page. However, if these libs call an element in the body tag, there’ll be a response (still from the head tag). When I try to call an element from the head, there is no response – why?
Thanks in advance. 🙂
The browser parses the html page from top to bottom, executing any
<script>blocks in place as it finds them. Which means if the JavaScript attempts to access elements on the page it can only see those included higher in the page because the ones lower down have not been parsed yet.There are two ways to deal with this:
Put your
<script>block at the bottom, just before the closing</body>tag (or at least put it after the elements it needs to reference), and/orUse an
onload(or, if you like jQuery, a$(document).ready()) handler.One way to setup an
onloadhandler is like this:You may have also seen something like this:
Where
someFunction()can be defined in a<script>block in the<head>. It’s basically the same thing, but it’s so 1990s to do it with an attribute in the html like that. (Actually even thewindow.onload()is out of date now, but it works and I don’t have time to explain the.addEventListener()method.)