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

前端 未结 10 1031
谎友^
谎友^ 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 13:17

    If it helps you:

    var document_on_ready = new Array();
    
    function on_ready(){
       for(i=0;i<document_on_ready.length;i++){
          document_on_ready[i].call();
       }
    }
    $(function(){
       on_ready();
    });
    
    var counter = 0;
    document_on_ready.push(function(){
       counter++;
       console.log('step1: ' + counter);
    });
    
    document_on_ready.push(function(){
       counter++;
       console.log('step2: ' + counter);
    });
    
    window.setTimeout(on_ready,1000);
    
    0 讨论(0)
  • 2020-11-30 13:19

    In some cases you need to add more code (scripts) in another places of the code, so creating a function limit you to write all the code in the same area. This why I prefer to add my custom events, and then trigger them:

    //Add a page Ready custom event
    $( document ).on( "page.ready", function( event ) {
        //Your Ready Scripts
    });
    
    //Add a page Load custom event
    $( document ).on( "page.load", function( event ) {
        //Your Load Scripts
    });
    
    //Trigger Ready scripts on page ready
    jQuery(function($) {
        $( document ).trigger( "page.ready" );
    });
    
    //Trigger Load scripts on page load
    $(window).load(function () {
        $( document ).trigger( "page.load" );
    });
    
    //Trigger the Custom events manually
    $( document ).trigger( "page.ready" );
    $( document ).trigger( "page.load" );
    

    https://learn.jquery.com/events/introduction-to-custom-events/

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

    What if you tried building a module execution controller right into the ready function? Kind of like this:

    https://gist.github.com/miguel-perez/476046a42d229251fec3

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

    I can see one scenario where this would be very useful, that is if you delay loading jQuery until everything else has loaded, then you dynamically append a new script element to load jQuery.

    In this case, $(document).ready is not always triggered, since in many cases the document will have completely loaded before jQuery is done loading and has set up the right event handlers.

    You could use named functions and call those instead, but it would still break any plugin that relies on $(document).ready.

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