The placement of scripts indicates dependencies: if script A needs some values from script B, then script B is placed above script A. For example: some JavaScript requires jQuery, so you place jQuery above any script that requires it.
That’s because scripts run from top to bottom.
Some scripts require the DOM to be loaded, e.g. they operate on some HTML elements, i.e. they use document.getElementById
or $("selector")
. In those cases the HTML elements are required by the script, so those elements need to be above the JavaScript that requires them, or in other words, the JavaScript that requires some HTML elements needs to be placed below those.
There are other options for dealing with this, e.g. utilizing window.addEventListener("DOMContentLoaded", function(){
…})
or jQuery’s $(document).ready(function(){
…})
. These options add event listeners that run later, whenever an event is fired.
Another, newer alternative is the defer
attribute.
More details at Why does jQuery or a DOM method such as getElementById not find the element?.
Sometimes, scripts are also put at the bottom to load the content of the page faster, because the scripts have to be downloaded and the content is only loaded after the scripts. You could use the async
attribute as an alternative to that.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…