Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running jQuery after all other JS has executed

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?

like image 722
jerome Avatar asked Mar 31 '11 02:03

jerome


People also ask

Can I use both JavaScript and jQuery together?

jQuery is a JavaScript library, so it operates on top of JavaScript. It cannot exist on its own, so you can't use one over the other. You can use just JavaScript or JavaScript and jQuery. jQuery was introduced to make development with JavaScript easier.

Does JS run in order?

JavaScript is synchronous. This means that it will execute your code block by order after hoisting. Before the code executes, var and function declarations are “hoisted” to the top of their scope.

How jQuery is executed?

The purpose of using jQuery is to make the javascript code easy to execute on the website, as jQuery wraps the many lines of code written in javascript, into a method that can be called with a single line of code. For this reason, a lot of common tasks that require javascript can be taken by jQuery.

Which jQuery function prevents the code from running before the loading of the document finishes?

The Document Ready Event This is to prevent any jQuery code from running before the document is finished loading (is ready). It is good practice to wait for the document to be fully loaded and ready before working with it.


1 Answers

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);
});
like image 112
Matt Ball Avatar answered Oct 01 '22 06:10

Matt Ball