Reputation: 9281
I have an an MVC 2 web application that uses Master pages. In the master pages, there are several ready blocks just like the one below scattered throughout the file
$(document).ready(function () {
...
});
Likewise, many of my views also have multiple ready blocks scattered throughout.
I have been asked to introduce another ready block into the Master that will run last.
My question is "Is there a way to guarantee that this new ready block will run last?". My thought was that if I put it at the very bottom of the Master page that would do it but I can't seem to convince myself that this is certain.
Upvotes: 6
Views: 622
Reputation: 6914
Here's a trick i use. In the Master Page, declare
var postReadyEvents = [];
Then, in the child pages, when you have a bit of code that needs to run last, do
postReadyEvents.push(function() {
///your stuff - I usually use this to resize a grid or something.
});
Now, in the Master Page $(document).ready(), do
for(var i = 0; i < postReadyEvents.length; i++)
{
postReadyEvents[i]();
}
When you have $(document).ready() on both child pages and Master Pages, the child page runs first and the Master Page runs last. This approach gives you the ability to control when a certain block of code runs.
Upvotes: 1
Reputation: 32158
This is the jQuery's .add
method that is called to push your $(document).ready()
's 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's callback
So: what it basically does is pushing all the functions inside the list
array and after the event has been triggered - call them in the same order and if your function has been pushed last - it will be called last.
To push it last you can declare it even in the head after including all other .js
files
(just make sure that there aren't any other $(document).ready()
below)
Upvotes: 5
Reputation: 9242
I think you can do a little trick here. as I don't know the exact case that should fit your solution, I suggest that you add a delay via
window.setTimeout(
a call to your cuntion here,*delay time in milliseconds*);
I know it's not that elegant, but this is what I thought about, let me know if this helped you, thanks.
Upvotes: 0