head.ready()与$(document).ready [英] head.ready() vs. $(document).ready

查看:82
本文介绍了head.ready()与$(document).ready的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近发现了 head.js 库,我对它感到满意,尽管我仍然有些困惑大约一件事.

Recently discovered the head.js library and boy am I happy with it, although I'm still a bit confused about one thing.

来自headjs.com:

From headjs.com:

脚本到达时,已经触发了"DOM就绪"事件,例如$(document).ready().如果加载的脚本取决于该事件,请确保您的库可以处理此事件. jQuery 1.4及更高版本有效.

The "DOM ready" event such as $(document).ready() is already fired when the scripts arrive. If the loaded scripts depend on that event make sure your library can handle this. jQuery 1.4+ works.

考虑到这一点,如果$(document).ready()中的代码依赖于head.js加载的外部脚本,那么设置使用jQuery的页面的最佳方法是什么?

With this in mind, what is the best way to set up a page that uses jQuery if the code within $(document).ready() depend of the external scripts loaded with head.js?

我们能不能只丢掉$(document).ready()调用而仍然成功地建立依赖于文档准备就绪的事件监听器之类的东西?例如:

Can we just lose the $(document).ready() call all together and still successfully set up things like event listeners which rely on the the document being ready? Ex:

head.js("script1.js", "script2.js", "script3.js", function() {
    $('#button').click(function(event) {
        alert("clicked");
    });
});

还是我们要在函数中包装$(document).ready()?

Or do we want to wrap $(document).ready() within the function?

只是想知道什么是最佳实践,以确保一切都准备就绪就可以使用了.

Just wondering what the best practice is to ensure that everything is ready to go by the time it needs to be.

推荐答案

两种方法都可以.如果DOM已经完全初始化,则立即调用传递给 ready()的处理程序.

Either way is fine. Handlers passed to ready() are called immediately if the DOM is already fully initialized.

为了获得较小的性能,可能要删除ready处理程序并直接包含代码,除非您依赖副作用,例如将jQuery的$对象传递给处理程序.

For a small performance gain, you may want to remove the ready handler and include your code directly, unless you're relying on a side effect like jQuery's $ object being passed to the handler.

这篇关于head.ready()与$(document).ready的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆