Limit usage of $(document).ready(function() { })
How can I check 开发者_如何学运维that my document only has one instance of $(document).ready(function()
?
If it's included more than one time, can I somehow remove duplicate instances (similar to PHP's require_once();
function)?
Are you saying that the exact same code could be added more than once?
If so, I suppose you could set a global property indicating if the code inside has already run, then test for that property inside the ready()
handler.
$(document).ready(function() {
// check a flag to see if this has been called yet
if( !window.thisCodeHasRun ) {
// set the flag to show this has been called
window.thisCodeHasRun = true;
/* run your code */
}
});
It would be better to take care of this on the server side, but if you must do it client side, this should work.
One option is to use bind and unbind:
$(document).bind("ready",function(){
console.log("zero");
});
$(document).bind("ready",function(){
console.log("one");
});
// get rid of previous ready events
$(document).unbind("ready");
$(document).bind("ready",function(){
console.log("two");
});
In the above, the first and second ready events will never fire because unbind has been called. So you will get "two" in the console.
精彩评论