Is there a limit to the number of "$document.ready" functions you can have on the same page with jQuery?
I have a simple JavaScript file that has three jQuery "$document.ready" functions. All three attach a facebox modal dialog to various links on my page.
This means I'm calling "$document.ready" three times.
First of all, is this advisable? Is it something I should avoid doing开发者_Go百科?
The app works fine but I'm wondering browsers prefer one "$document.ready" function.
I'm not sure what the best practices are here. Here's the code (it's a rails app):
$(document).ready(function() {
$('#login-link').facebox({
loadingImage : '/images/loading.gif',
closeImage : '/images/closelabel.gif',
});
$.facebox.settings.opacity = 0.75;
$(document).bind('reveal.facebox', function() {
$('#new_user_session').submit(function() {
$.post(this.action, $(this).serialize(), null, "script");
return false;
});
});
});
$(document).ready(function() {
$('#contact-link').facebox({
loadingImage : '/images/loading.gif',
closeImage : '/images/closelabel.gif',
});
$.facebox.settings.opacity = 0.75;
$(document).bind('reveal.facebox', function() {
$('#new_contact').submit(function() {
$.post(this.action, $(this).serialize(), null, "script");
return false;
});
});
});
jQuery(document).ready(function($) {
$('a[rel*=facebox]').facebox()
})
Now, it would be fairly easy to refactor this code into one "$document.ready" method but I would only do that if it was advisable, cos it's cleaner the way I've got it right now.
No there is no limit and the only reason you would HAVE to refactor is to control order of execution.
Browser js engines know nothing of $().ready. This is a jquery function that is designed to provide consistent behavior across platforms.
You are doing just fine.
精彩评论