how can i invoke a function after page is done loading? (and only then..)
I'm having trouble with some jquery code.
in my HTML page I use ajax to get some info, and then I'm changing an HTML element
with $("#id").html(...)
.
The problem is, I also have a $(document).ready
code which I wanna call only once
when the page is done loading, but after each change in the html with the $("#id").html(...)
the code is called once again.
How can I run the $(document).ready
code only once?
Here is an example:
$(document).ready(function(){
// this code will开发者_如何学JAVA run not only once...
}
function f(){
$("#id").html(...);
}
Try:
var run = false;
$(document).ready(function() {
if(!run) {
...
run = true;
}
});
...or...
$(window).load(function() {
...
});
The first one will make sure it is only run once; the 2nd one is run when the entire page is finished loading (useful if you need to resize things once images have finished loading).
From the comments on the .ready
documentation:
Looks like .ready() fires not only when page initially has settled the DOM, but apparently also after changes to the DOM. This is an issue if your ready handler changes the DOM. That will result in ready() firing more than once. It may result in an endless loop if each invocation adds yet more to the DOM. Firefox and IE behave differently to this, including different error messages, and leaving the page display in different states. So, if ready() modifies the DOM, then it would be wise to have a way to check whether ready has already been fired.
Replying to self: Well it appears that part of the problem is not that the ready function fires again (though that is possible aparently), but that changing the DOM causes the script that creates the ready function to fire again, adding an additional ready function, etc etc. This seems to happen if the javascript is embedded in the html at a point beyond (or contained in) the part of the DOM that the ready handler modifies. (Obviously would be better to put script that creates a ready function in the document head, but in this case that's not an option.) Problem fixed by checking a global flag variable to be undefined before executing jQuery(document).ready(...).
If this might be your problem, you can adopt the same solution:
var onLoadFired = false;
$(document).ready(function() {
/* Ensure this function only runs once */
if (onLoadFired) {
return;
}
else {
onLoadFired = true;
}
/* Business logic */
// .. your code here ..
});
Or, better, move your handler into a separate script file that's included by a script
tag in your page's head
element.
Try this:
$(window).bind("load", function() {
...
});
精彩评论