Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any overhead to having multiple $(document).ready with jQuery 1.8.1

I have code like this:

$(document).ready(function () {

    $('.accessLink')
        .bind('click', accessLinkClick);
    $('#logoutLink')
        .click(function (e) {
            window.location = $(this).attr('data-href')
        });

});

Functionality for each part of my site is divided into a number of small files and when the site is deployed these are mimified and joined up.

Each of these small files which number up to ten wait on $(document).ready. Can anyone tell me if there is much overhead in doing this. Splitting my code into functional areas has meant the code looks easy to maintain but I am just wondering about overhead now that I am using jQuery 1.8.1

Update:

Based on the answers I started to code like this:

$(document).ready(function () {

    accessButtons(); // login, register, logout
    layoutButtons();
    themeButtons();  // theme switcher, sidebar, print page

});

with each function then coded as:

function accessButtons() {

    $('.accessLink')
        .bind('click', accessLinkClick);
    $('#logoutLink')
        .click(function (e) {
            window.location = $(this).attr('data-href')
        });

};
like image 726
Alan2 Avatar asked Dec 04 '22 14:12

Alan2


2 Answers

Here's the difference between 10 $(document).ready() calls versus one that then calls 10 initialization functions.

With the 10 calls, you get:

  • 10 calls to $(document).
  • 10 calls to the .ready() method.
  • One event listener for the DOM ready event
  • When the DOM ready event fires, it then cycles through an array of callbacks and calls each callback passed to .ready().

If you have one $(document).ready() that then called all 10 of your initialization functions, you would have this:

  • 1 call to $(document).
  • 1 call to the .ready() method.
  • One event listener for the DOM ready event
  • When the DOM ready event fires, it then calls your one ready handler.
  • Your ready handler then calls the 10 initialization function calls.

So, the difference is approximately the time it takes to construct 9 extra jQuery objects and make 9 extra .ready() method calls. In extreme cases this could be noticeable, but it is unlikely that you would see a difference in practice.

like image 100
jfriend00 Avatar answered Dec 07 '22 02:12

jfriend00


If the code needs to be executed in order, then they should in the same dom ready callback function, otherwise, you could divide them into different dom ready callback.

like image 39
xdazz Avatar answered Dec 07 '22 02:12

xdazz