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

2019-04-18 05:02发布

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?

3条回答
三岁会撩人
2楼-- · 2019-04-18 05:03

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楼-- · 2019-04-18 05:16

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

查看更多
闹够了就滚
4楼-- · 2019-04-18 05:24

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/

查看更多
登录 后发表回答