Mathijs Beks Mathijs Beks - 3 months ago 17
Javascript Question

Is having 100 document ready better or worse than 1 document ready?

Just wondering if the amount of document ready-calls affects page speed.
Is there a way in Gulp / Grunt to uglify / minify JS by removing seperate document ready functions?

Answer

Just check it!

I don't see significant difference in Chrome.
As I know, it was critical for IE8, but didn't check this fact.

Also, seems like jQuery already aggregates load events.

for (var q=0; q<1000; ++q) {
  document.addEventListener('DOMContentLoaded', (function (i) {
    console.log(i);
  }).bind(null, q));
}

document.addEventListener('DOMContentLoaded', function () {
  document.querySelector('output').textContent = performance.now().toFixed(3);
});
<output></output>

document.addEventListener('DOMContentLoaded', function () {
  for (var q=0; q<1000; ++q) {
    (function (i) {
      console.log(i)
    }).bind(null, q)();
    
    document.querySelector('output').textContent = performance.now().toFixed(3);
  }
});
<output></output>

for (var q=0; q<1000; ++q) {
  $((function (i) {
    console.log(i);
  }).bind(null, q));
}

$(function () {
  document.querySelector('output').textContent = performance.now().toFixed(3);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<output></output>

$(function () {
  for (var q=0; q<1000; ++q) {
    (function (i) {
      console.log(i)
    }).bind(null, q)();
    
    document.querySelector('output').textContent = performance.now().toFixed(3);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<output></output>