Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(document).ready() and initializing jQuery at the end of the page

Let me get this straight. According to best practice we should initialize jQuery at the bottom of the page. If we do that, any reference to the jQuery object (ie. $ or jQuery) above the reference will be a null. However, as for $(document).ready(), the reason why this jQuery function is ever needed is when you want to delay an execution of a function after the page has loaded. This seems to be a conflict.

How do I use the functionality of $(document).ready() at the top of the page and still reference jQuery at the bottom of the page? I think jQuery should be initialized at the top of the page for this very reason.

like image 202
burnt1ce Avatar asked Nov 05 '10 16:11

burnt1ce


2 Answers

If you're going to put your scripts at the bottom of the page for efficiency purposes, and there are no further elements (beyond </body> and </html>) you wont even need to use $(document).ready(...);.

Placing your code at the top of the page makes sense semantically, and the loading time "savings" is negligible in most cases. It really only makes a difference when the scripts are enormous, or when the scripts are on another server that may or may not be active.

If you're live-linking jQuery, i'd suggest putting it at the bottom of the page. If you're local-linking jQuery, the top should be fine. Just make sure to use minimized code.

like image 120
zzzzBov Avatar answered Oct 14 '22 04:10

zzzzBov


Just put $(document).ready below where you initialize jQuery regardless of where that is.

In reality though you should be putting all your JS at the bottom, even $(document).ready.

like image 23
Loktar Avatar answered Oct 14 '22 05:10

Loktar