Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a limit to the number of "$document.ready" functions you can have on the same page with jQuery?

Tags:

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?

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.

like image 992
stephenmurdoch Avatar asked Jan 20 '26 18:01

stephenmurdoch


1 Answers

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.

like image 87
Sky Sanders Avatar answered Jan 26 '26 02:01

Sky Sanders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!