I have been using templates such as bootstrap templates for a while and as i try to modify or add more script, i always encounter these two scenario
SCENARIO 1: in some templates, the scripts only works when they are placed at the top i.e. head. but does not work while at the bottom of the elements
<head>
<!--required scripts here e.g.-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
</head>
<body>
<div class="content">
<!--elements that require scripts i.e. forms and button-->
</div>
<footer>
</footer>
</body>
SCENARIO 2: in some templates, the scripts only works when they are placed at the bottom i.e. footer. but does not work when placed at the top of the elements
<head>
</head>
<body>
<div class="content">
<!--elements that require scripts i.e. forms and button-->
</div>
<footer>
<!--required scripts here e.g.-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
</footer>
</body>
I rely wanted to understand the idea behind these scenarios. What is it that causes such behavior? Or what should one consider?
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.
Javascript runs one thing at a time. Generally it runs code at the top first. Therefore you cannot ask for variables or functions before code has run that declares them. ex:
<script> var one = 1 </script>
<script> console.log(one) </script>
will log out 1 however:
<script> console.log(one) </script>
<script> var one = 1 </script>
will log out undefined.
In your example, I assume that the code broke because it needed jquery but jquery was loaded after the code tried to run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With