How to write jQuery code before loading it?

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 it?

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();

Then, write your jQuery dependent codes in function and push the function to the above declared array.

<script type="text/javascript">
          //write your codes here

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){

Here you are calling all the previously added functions, that is you are executing your codes now.


Though you are placing your jQuery code at the top, that doesn't mean they will be executed there, rather they will be executed after you have loaded jQuery.


If you use separate files for header and footer and body (template) then this is very useful. If you think that "Why to write codes above when it will actually execute later below", then think of writing all jQuery codes of all content page in the footer, wouldn't it be hard manage these codes, hard to make changes? Moreover, why load all the codes of all pages all the time (as your footer will be loaded always)? Right, that is why, this technique is useful.

Recommended Recommends


Contact Us