Running jQuery after executing all other JS

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

+8
javascript jquery dom dynamic
source share
5 answers

If you know what elements to expect, you can use setInterval to poll the DOM to see when they were inserted. For example, this way you can poll the element with the identifier foo :

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

Even if you cannot change the download order, can you change the way it is downloaded?

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

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

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

+2
source share

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

Example:

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

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

+1
source share

The problem was trying to declare a variable to hold the jQuery object before the object was on the page. Moving these declarations inside the code block, which was performed only after the click event, which was associated only after $ (window) .load, solved the problem.

Thanks everyone for the advice!

+1
source share

If another script is executed completely in the load event, you can add a handler to the same event and put your code in the setTimeout call (with a delay of 1 ), which will force your code to execute during the next break.

0
source share

All Articles