Running jQuery after all other JS has executed

24,544

Solution 1

If you know what elements to expect, you can use setInterval to poll the DOM to see when they've been inserted. For example, this is how you could poll for an element with ID foo:

$(window).load(function ()
{
    var i = setInterval(function ()
    {
        if ($('#foo').length)
        {
            clearInterval(i);
            // safe to execute your code here
        }
    }, 100);
});

Solution 2

Even though you cannot change the load order, can you change how it is loaded?

One thing I have used in the past when I wanted to load some javascript and execute some code after I was sure that it had finished loading is jquery's $.getScript:

$.getScript('javascripttoload.js', function() {
        //do the DOM manipulation you were talking about...
});

http://api.jquery.com/jQuery.getScript/

Solution 3

The problem was trying to declare a variable to store the jQuery object before the object was on the page. Moving those declarations inside of a code block that was only executed after a click event which was only bound after $(window).load solved the problem.

Thanks all for the tips, though!

Solution 4

If you need to attach an event handler to future DOM nodes, you could use jQuery .live(), otherwise, you can use livequery plugin.

example:

$(".nodes").livequery(function () {
    // do something with the nodes
}

which will call the supplied anonymous function for all current and future nodes with the class .nodes

Share:
24,544
jerome
Author by

jerome

Updated on July 09, 2022

Comments

  • jerome
    jerome almost 2 years

    In the past, I have used $(window).onload to run a block of code after other scripts have loaded. In this case I don't have the ability to change the loading order of the JS files and the code that I am concerned with needs to manipulate DOM nodes that are dynamically inserted by another JS file that is loaded further down the page. Both scripts are located near the bottom of the document. Does anyone have any suggestions for this scenario?

  • RobG
    RobG about 13 years
    For such functions it is much more efficient to use document.getElementById('foo').
  • Matt Ball
    Matt Ball about 13 years
    It's true that document.getElementById is more efficient, but then again, jQuery isn't used for its raw performance. It's also optimized for this sort of simple selector. More to the point: there will be no perceptible difference between the two, since this function will be executed at a relatively slow, and fixed, rate.