Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript - head, body or jQuery?
    primarykey
    data
    text
    <p>This question is just to clear some things up. Some things like this have been asked before, and this rounds them all up into one question - where should JavaScript go in the HTML document, or, more importantly, does it matter? So, one of the things I'm asking is, does</p> <pre><code>&lt;head&gt; &lt;script type="text/javascript"&gt; alert("Hello world!"); &lt;/script&gt; &lt;/head&gt; </code></pre> <p>at all differ (in terms of functionality) from</p> <pre><code>&lt;body&gt; &lt;!-- Code goes here --&gt; &lt;script type="text/javascript"&gt; alert("Hello world!"); &lt;/script&gt; &lt;/body&gt; </code></pre> <p>More importantly, I want to focus on JS that modifies or uses elements from the DOM in any way. So I know that if you put something like <code>document.getElementById("test").innerHTML = "Hello world!"</code> before <code>&lt;element id="test"&gt;&lt;/element&gt;</code> in your body, then it won't work since the body is loaded from top to bottom, making the JS load first, which will then proceed to try to manipulate an element that doesn't exist yet. So it should, just like the above, either go in the <code>&lt;head&gt;</code> or just before the <code>&lt;/body&gt;</code> tag. The question is, aside from organisation and sorting, does it matter which one of these is chosen, and if so, in what way?</p> <p>Of course, there is also a third method - the jQuery way:</p> <pre><code>$(document).ready(function(){ /*Code goes here*/ }); </code></pre> <p>That way, it doesn't matter where in the body you place the code, since it will only be executed when everything has loaded. The question here is, is it worth importing a huge JS library <em>just</em> to use a method the need for which could be replaced with an accurate placing of your scripts? I'd just like to clear things up a little here, if you would like to answer, go ahead! Summary: where should different kinds of scripts go - head or body, and/or does it matter? Is jQuery worth it just for the ready event?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload