How to make sure my jQuery.ready works at the end

I have an MVC 2 web application that uses master pages. There are several ready-made blocks on the main pages, as shown below, scattered throughout the file.

$(document).ready(function () { ... }); 

In addition, many of my views also have many ready-made blocks scattered around the world.

I was asked to enter another finished block in the Master, which will work last.

My question is: "Is there a way to guarantee that this new finished block will work last?". I thought that if I put it on the very bottom page of the wizard who would do this, but I canโ€™t convince myself that itโ€™s for sure.

+6
source share
3 answers

This is the jQuery .add method, which is called to call the $(document).ready() callback to the list of all callbacks:

 add = function( args ) { var i, length, elem, type, actual; for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { // Inspect recursively add( elem ); } else if ( type === "function" ) { // Add if not in unique mode and callback is not in if ( !flags.unique || !self.has( elem ) ) { list.push( elem ); } } } } 

source: jQuery callback

So: that basically it pushes all the functions inside the list array, and after the event has been fired, call them in the same order, and if your function was last pressed, it will be called last.

To click it, you can declare it even in your head after including all other .js files (just make sure there are no other $(document).ready() below)

+5
source

Here is the trick I'm using. On the main page, announce

 var postReadyEvents = []; 

Then, on the child pages, when you have some code to be executed last, execute

 postReadyEvents.push(function() { ///your stuff - I usually use this to resize a grid or something. }); 

Now, in the main page of $ (document) .ready (), do

 for(var i = 0; i < postReadyEvents.length; i++) { postReadyEvents[i](); } 

When you have $ (document) .ready () on both the child pages and the main pages, the child page starts first and the main page starts last. This approach gives you the ability to control when a specific block of code is executed.

+1
source

I think you can do a little trick here. since I donโ€™t know the specific case that should fit your decision, I suggest you add a delay through

window.setTimeout( call to your cuntion here, * delay time in milliseconds *);

I know that this is not so elegant, but I thought about it, let me know if this helped you, thanks.

0
source

Source: https://habr.com/ru/post/900619/


All Articles