head.ready() vs. $(document).ready

Deadly 提交于 2019-12-07 08:30:47

问题


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

From headjs.com:

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.

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?

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");
    });
});

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.


回答1:


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

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.



来源:https://stackoverflow.com/questions/12221122/head-ready-vs-document-ready

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