Do jQuery scripts still need $(document).ready if they are loaded after all of the page HTML?

对着背影说爱祢 提交于 2019-12-22 02:05:34

问题


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/



来源:https://stackoverflow.com/questions/10392803/do-jquery-scripts-still-need-document-ready-if-they-are-loaded-after-all-of-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!