128

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.

7 Answers 7

236

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
});
9
  • 1
    can I import external scripts using this method?
    – chrism
    Commented Jun 18, 2009 at 13:05
  • 1
    Sure, if you are already doing this inside $(document).ready(), this will be no different. Commented Jun 18, 2009 at 14:43
  • 8
    This answer was useful to me because I didn't realise that jquery code gets run in sequence Commented May 4, 2011 at 9:52
  • 1
    Thank you SO much! This fixed my .height() issue where it wasn't getting the correct height because the page (apparently) wasn't loaded yet.
    – Jon
    Commented Mar 18, 2013 at 1:04
  • 12
    In JQuery 3.0, you should use the syntax $(window).on('load', function() { }); since $(window).load() is deprecated.
    – Alex
    Commented Jul 21, 2016 at 6:06
21

This code block solve my problem,

<script type="text/javascript">
  $(window).bind("load", function () {
    // Code here
  });
</script>

3
  • How can you run a jQuery function to see if jQuery is already loaded? This will work only when jQuery has loaded prior to the checking.
    – HelpNeeder
    Commented Dec 5, 2017 at 2:14
  • 1
    Great, it works! Commented Sep 28, 2021 at 18:05
  • This one absolutely works for me! Thank you a million
    – Mego
    Commented Apr 8, 2022 at 20:33
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>
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> 
2
  • 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
    Commented Jun 18, 2009 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. Commented Jun 18, 2009 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.

5
  • 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
    Commented Jun 18, 2009 at 11:29
  • $(document).ready(function(){ callLoadFunction1(); callLoadFunction2(); calljQueryLoadFunction(); }); Commented Jun 18, 2009 at 11:31
  • the other scripts are all external files so i'm not sure this would work would it?
    – chrism
    Commented Jun 18, 2009 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. Commented Jun 18, 2009 at 12:05
  • 2
    Just use $(window).load(function(){...}) Commented Jun 18, 2014 at 17:37
0

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.

1
  • 9
    Happy that you found a solution but your answer is not the useful for others without more details...
    – Andrew
    Commented Jan 16, 2019 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.