Do jQuery scripts still need $(document).ready if

2019-04-18 04:31发布

问题:

If I'm loading my jQuery scripts below all of my page HTML, do I still need to wait for $(document).ready to be able to use jQuery to find elements in the page?

回答1:

No because the document would have already been loaded. The Dom loads top to bottom. I personally like to put all my js at the bottom of the page instead of in the head.

however it is only 1 line of code and i would suggest using it just to be safe. also you can make it even shorter. $(function() {} is the same as $(document).ready(function(){})



回答2:

No you do not need $(document).ready for any code that interacts with DOM elements on the page if the scripts are placed below these elements.

It's good practice to put them before the closing </body> tag.



回答3:

You do not need to use jQuery's ready function, but your code would have to be written with this in mind. Any click or other bind-based handlers may not attach to selectors correctly, however, others like live and $.ajax may function as intended.

Be careful when using script loaders or AMD using this approach. jQuery must be available and you must block when loading. Load jQuery and other deps in the head.

A great look at this technique which describes that this is not necessary to use for jQuery to function (not necessarily about the use in footer):

http://encosia.com/dont-let-jquerys-document-ready-slow-you-down/