127

I have a jquery script which I need to run only once everything else on the page, including some other javascripts (over which I have no control) have finished doing their thing.

I though perhaps there was an alternative to $(document).ready but I haven't been able to find it.

chrism
  • 2,905
  • 8
  • 37
  • 40

7 Answers7

235

You can have $(document).ready() multiple times in a page. The code gets run in the sequence in which it appears.

You can use the $(window).load() event for your code since this happens after the page is fully loaded and all the code in the various $(document).ready() handlers have finished running.

$(window).load(function(){
  //your code here
});
Jose Basilio
  • 50,714
  • 13
  • 121
  • 117
21

This code block solve my problem,

<script type="text/javascript">
  $(window).bind("load", function () {
    // Code here
  });
</script>
Agah Toruk
  • 383
  • 5
  • 10
13

Multiple $(document).ready() will fire in order top down on the page. The last $(document).ready() will fire last on the page. Inside the last $(document).ready(), you can trigger a new custom event to fire after all the others..

Wrap your code in an event handler for the new custom event.

<html>
<head>
<script>
    $(document).on("my-event-afterLastDocumentReady", function () {
        // Fires LAST
    });
    $(document).ready(function() {
        // Fires FIRST
    });
    $(document).ready(function() {
        // Fires SECOND
    });
    $(document).ready(function() {
        // Fires THIRD
    });
</script>
<body>
... other code, scripts, etc....
</body>
</html>

<script>
    $(document).ready(function() {
        // Fires FOURTH
        // This event will fire after all the other $(document).ready() functions have completed.
        // Usefull when your script is at the top of the page, but you need it run last
        $(document).trigger("my-event-afterLastDocumentReady");
    });
</script>
Jason Williams
  • 2,740
  • 28
  • 36
3

From here:

// Add jQuery 
var GM_JQ = document.createElement('script'); 
GM_JQ.src = 'http://jquery.com/src/jquery-latest.js';
GM_JQ.type = 'text/javascript'; 
document.getElementsByTagName('head')[0].appendChild(GM_JQ); 

// Check if jQuery's loaded 
function GM_wait() 
{ 
    if(typeof unsafeWindow.jQuery == 'undefined') 
    { 
        window.setTimeout(GM_wait,100); 
    } 
    else 
    { 
        $ = unsafeWindow.jQuery; 
        letsJQuery(); 
    } 
} 

GM_wait(); 

// All your GM code must be inside this function 
function letsJQuery() 
{
    // Do your jQuery stuff in here    
} 

This will wait until jQuery is loaded to use it, but you can use the same concept, setting variables in your other scripts (or checking them if they're not your script) to wait until they're loaded to use them.

For example, on my site, I use this for asynchronous JS loading and waiting until they're finished before doing anything with them using jQuery:

<script type="text/javascript" language="JavaScript"> 
    function js(url){
        s = document.createElement("script");
        s.type = "text/javascript";
        s.src = url;
        document.getElementsByTagName("head")[0].appendChild(s);
    }       

    js("/js/jquery-ui.js");
    js("/js/jrails.js");
    js("/js/jquery.jgrowl-min.js");
    js("/js/jquery.scrollTo-min.js");
    js("/js/jquery.corner-min.js");
    js("/js/jquery.cookie-min.js");
    js("/js/application-min.js");

    function JS_wait() {
        if (typeof $.cookie == 'undefined' || // set in jquery.cookie-min.js
            typeof getLastViewedAnchor == 'undefined' || // set in application-min.js
            typeof getLastViewedArchive == 'undefined' || // set in application-min.js 
            typeof getAntiSpamValue == 'undefined') // set in application-min.js
        { 
            window.setTimeout(JS_wait, 100); 
        }
        else 
        { 
            JS_ready(); 
        }
    }

    function JS_ready() {
        // snipped
    };

    $(document).ready(JS_wait);
</script> 
Chris Doggett
  • 19,959
  • 4
  • 61
  • 86
  • This will only wait until jQuery is loaded and disregard other aspects of the page. It's nothing more than a hack for older versions of greasemonkey that don't support the @require directive. – Cheekysoft Jun 18 '09 at 11:42
  • 1
    I've added my code as an example of how I used the same concept with jQuery to wait until other code has loaded. – Chris Doggett Jun 18 '09 at 11:45
2

Have you tried loading all the initialization functions using the $().ready, running the jQuery function you wanted last?

Perhaps you can use setTimeout() on the $().ready function you wanted to run, calling the functionality you wanted to load.

Or, use setInterval() and have the interval check to see if all the other load functions have completed (store the status in a boolean variable). When conditions are met, you could cancel the interval and run the load function.

VK Da NINJA
  • 510
  • 7
  • 19
Richard Clayton
  • 7,452
  • 3
  • 23
  • 19
  • I'm not sure what you mean by this. Are you suggesting I import all the scripts through a jquery script and just put my script last? If so what would that look like (I'm a designer by trade, so don't use big words :)) – chrism Jun 18 '09 at 11:29
  • $(document).ready(function(){ callLoadFunction1(); callLoadFunction2(); calljQueryLoadFunction(); }); – Richard Clayton Jun 18 '09 at 11:31
  • the other scripts are all external files so i'm not sure this would work would it? – chrism Jun 18 '09 at 11:33
  • @chrism: See my second example. It waits until variables are set indicating the other external JS files have loaded before it does anything. You just put the code you want to run last in my JS_ready() method. It does exactly what you're looking for. – Chris Doggett Jun 18 '09 at 12:05
  • 2
    Just use ```$(window).load(function(){...})``` – Ryan Taylor Jun 18 '14 at 17:37
1

It turns out that because of a peculiar mixture of javascript frameworks that I needed to initiate the script using an event listener provide by one of the other frameworks.

chrism
  • 2,905
  • 8
  • 37
  • 40
  • 7
    Happy that you found a solution but your answer is not the useful for others without more details... – Andrew Jan 16 '19 at 20:27
0

The following script ensures that my_finalFunction runs after your page has been fully loaded with images, stylesheets and external content:

<script>

    document.addEventListener("load", my_finalFunction, false);

    function my_finalFunction(e) {
        /* things to do after all has been loaded */
    }

</script>

A good explanation is provided by kirupa on running your code at the right time, see https://www.kirupa.com/html5/running_your_code_at_the_right_time.htm.

GCru
  • 426
  • 6
  • 8