简体   繁体   English

$(document).ready()并在页面末尾初始化jQuery

[英]$(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. 根据最佳实践,我们应该在页面底部初始化jQuery。 If we do that, any reference to the jQuery object (ie. $ or jQuery ) above the reference will be a null. 如果我们这样做,对引用之上的jQuery对象(即。 $jQuery )的任何引用都将为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. 但是,对于$(document).ready() ,之所以需要这个jQuery函数,是因为你想在页面加载后延迟函数的执行。 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? 如何在页面顶部使用$(document).ready()的功能,并仍然在页面底部引用jQuery? I think jQuery should be initialized at the top of the page for this very reason. 我认为jQuery应该在页面顶部初始化,原因就在于此。

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(...); 如果为了提高效率而将脚本放在页面底部,并且没有其他元素(超出</body> and </html> ),您甚至不需要使用$(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. 如果你是实时链接jQuery,我建议把它放在页面的底部。 If you're local-linking jQuery, the top should be fine. 如果你是本地链接jQuery,顶部应该没问题。 Just make sure to use minimized code. 只需确保使用最小化的代码。

Just put $(document).ready below where you initialize jQuery regardless of where that is. 只需将$(document).ready放在初始化jQuery的地方,无论它在哪里。

In reality though you should be putting all your JS at the bottom, even $(document).ready . 实际上,你应该将所有的JS放在底部,甚至是$(document).ready

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM