开发者

jQuery: Intercept original DOM ready event?

Would it be possible to somehow intercept the DOM ready event so that anything normally triggered within, say, $(document).ready(function() { ... } wo开发者_StackOverflow中文版uld not be executed? And then later manually trigger the event so that the code was executed?

In my case, I have a large amount of existing code that already relies on $(document).ready(function() { ... } and my hope is that I would not have to do a search/replace to have all of it rely on a custom manually triggered event.


jQuery.trigger() is made for such need

Any event handlers attached with .bind() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user:


If you do not want something to be "normally" triggered, it should not be in $(document).ready(on_ready_func). Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.

Instead, from on_ready_func cherrypick the things you want to trigger manually into another function say manual_func, and call that function at event of your choice.

Note that, ready function cannot be triggered using trigger, so you cannot fire the func again, unless you have it as a separate function.

Split-up is your best option.

var manual_func = function(){
    // Manual loads
}

var on_ready_func = function(){
    // only things to be loaded on dom ready
    // e.g.

    $('button#load_manual_trigger').bind('click', manual_func);
}

$(document).ready(on_ready_func);

Happy Coding.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜