jQuery and various other JS source files are regular part of website built nowadays. But this is always suggested to load JS files at the end of the document. In that case, how you are going to write JS code that requires jQuery to be loaded?
In one of my Web Development tutorial called 10 tips to speed up your website, I also suggested that you should load your JS files at the end of the document.
5. Put JavaScript at bottom:
This is also good practice in site optimization that you load your JS files just before your footer. This will let the browser draw the page without being blocked by JS files loading.
But the problem is, if you load jQuery at the end of the document and try to write jQuery code before that, you will get errors like $ is not defined. So how to write jQuery code before loading jQuery then!
How to write jQuery code before loading jQuery:
So here is the way you can do this. Simply write all your codes in functions and push these functions to a JS array. Later, at footer, after loading jQuery, loop through this array and call every function to run the codes.
Write the following code at the top of the document.
<script type="text/javascript">
var jQ = new Array();
</script>
Then, write your jQuery dependent codes in function and push the function to the above declared array.
<script type="text/javascript">
jQ.push(function(){
//write your codes here
});
</script>
You can do this as many times as required. What’s happening here is that you are queuing up codes in an array.
At the end of the document, in the footer section, where you are loading jQuery, after that line, write the following lines of code.
<script type="text/javascript">
for(var i in jQ){
jQ[i]();
}
</script>
Here you are calling all the previously added functions, that is you are executing your codes now.