How to trigger $().ready() in jQuery?

前端 未结 10 1030
谎友^
谎友^ 2020-11-30 12:49

Using jQuery, is there a way to retrigger the document.ready trigger at some point after a page has loaded?

Update: jQuery sheds them once they are run.

相关标签:
10条回答
  • 2020-11-30 12:58

    Aaron - what would you be trying to accomplish, reinitializing variables?

    Edited... The beauty of jQuery in my opinion is the call back functions. Why not just have some action/function executed after the event.

    0 讨论(0)
  • 2020-11-30 13:02

    If you just need to make sure that new initialization functions get run, you don't need to do anything. When you add a new event handler in $().ready, after the document finishes loading, it will run immediately.

    Apparently, calling $().trigger("ready") directly doesn't work because jQuery resets the ready event handlers after it runs them. You will need to keep track of the functions you need to call, and call them directly as below.

    Of course, it might be better to just call the function directly, so you don't re-run something you didn't intend to (some plugins might have their own $().ready() functions that they don't expect to run twice).

    $().ready(initializationFunction);
    
    // later:
    initializationFunction(jQuery);
    
    0 讨论(0)
  • 2020-11-30 13:07

    ASP.Net UpdatePanel partial page loads are another place where one might want to re-trigger loading functionality - not that $().ready is the right place to do that. In that case, you can either use page_load or the MS framework's endrequest event.

    0 讨论(0)
  • 2020-11-30 13:10

    You can do something like this:

    $(document).on('ready readyAgain', function() {
        // do stuff
    });
    
    // At some other point in time, just trigger readyAgain
    $(document).trigger('readyAgain');
    

    Note:

    $(document).on('ready') has been deprecated in jQuery 1.8 according to documentation. An alternative method is as follows:

    function myReadyFunction(){}
    $(myReadyFunction);
    
    // at some other point, just call your function whenever needed:
    myReadyFunction($);
    
    0 讨论(0)
  • 2020-11-30 13:10

    You should be able to with document.ready.apply();

    0 讨论(0)
  • 2020-11-30 13:15

    Easy: you just need to disable the safety-flag jQuery.isReady. Set jQuery.isReady to false and use jQuery(document).trigger('ready') to re-trigger this event. That's quite useful for turbolinks-style navigation.

    0 讨论(0)
提交回复
热议问题