PageSpeed OptiPic - optimización automática del sitio para los requisitos de Google Pagespeed Insights
JavaScript: Fusión, compresión, carga perezosa. CSS: compresión de tamaño y optimización de carga. Optimización de imágenes. Optimización de widgets de terceros y sistemas de análisis.

¿Es mejor o peor tener 100 document ready que 1 document ready?

Me pregunto si la cantidad de llamadas a document.ready afecta la velocidad de carga de la página. ¿Hay alguna manera en Gulp / Grunt de comprimir / minimizar JS eliminando las funciones independientes de document ready?

#1
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.
IE11 shows 2 seconds on the first snippet, when the others take 200 ms only.

Also, seems like jQuery already aggregates load events.

Don't forget

  1. When you are running same code in one tab, browser remembers something and runs it faster.
  2. Reload the page is not enought. Open a new tab instead.
  3. After opening a new tab, run snippets in different order.
  4. If the snippet is ran first on the tab, it will get additional slowdown, comparing the other three.

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>

Maybe it's just me as a JavaScript avoider, but none of the scripts have document.ready inside. If you JS guys talk about document.ready, that's a synonym for addEventListener('DOMContentLoaded')?

There are two events: DOMContentLoaded and load (window.onload). First of them occures when the body pasring is complete, but some assets are loading still. The second - when the page is completely loaded. First one is nice for running scripts with dom manipulations, but browsers not always had support of it.

So jQuery uses the first of these two events and classic form of subscription was

$(document).ready(function () {
  // ...
});

but after some versions if was simplified to passing function directly into jQuery:

$(function () {
  // ...
});

So in vanilla examples I'm using the first of 2 events, and in jQuery examples I'm using the short form of subscription on it. As browsers without support of this event are very old it's correct to assume that jQuery always uses DOMContentLoaded (probably the load way is removed in version 2 - didn't check it, but see no reasons to keep it there).

#2

Muchas llamadas listas de documentos no deberían afectar mucho el rendimiento de la aplicación. La mejor solución puede ser tener solo una y allí inicializar todo lo que necesites. Pero depende de la estructura de tu aplicación y es posible que te sientas más cómodo teniendo más de una. De todos modos, no creo que haya ninguna tarea de Gulp que envuelva diferentes funciones preparadas en una, porque eso afectará la lógica de la aplicación.

#3

Puedes tener varias, pero no siempre es lo más ordenado para hacer. Trata de no abusar de ellas, ya que afectará seriamente a la legibilidad. Aparte de eso, es perfectamente legal.

También vale la pena mencionar que una función definida dentro de un bloque $(document).ready no se puede llamar desde otro bloque $(document).ready.

$(document).ready(function() { alert('hola1'); function decirAlgo() { alert('algo'); } decirAlgo(); }); $(document).ready(function() { alert('hola2'); decirAlgo(); }); 

la salida fue

hola1 algo hola2

Verifica esta publicación y esta otra

#4

Yes, you can use multiple document ready handler, there is no special advantage even though you can use jQuery code in several place. You can’t use the variable inside one in another since those are in different scope.

Actually jQuery event handler pushing function for execution in queue of a particular event. When event is fired all functions executes one by one from particular events row/stack/queue based on return value of parent sequential function.
BUT There is one thing to note that each $(document).ready() function call must return. If an exception is thrown in one, subsequent calls will never be run.

$(document).ready(function() {
    document.write('<h3>In First ready function</h3>');
    var foo = function() {
        console.log('inside foo');
    }
    document.write("foo:" +(typeof foo)+"<br>");
    document.write("bar:" +(typeof bar)+"<br>");
    
});
$(document).ready(function() {
   document.write('<h3>In Second ready function</h3>');
    
    var bar=function bar() {
        console.log('inside bar');
    }
    document.write("foo:" +(typeof foo)+"<br>");
    document.write("bar:" +(typeof bar)+"<br>");
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Actually jQuery $(document).ready() method is attach function with DOMContentLoaded event using addEventListener method.

Yes you can have multiple instance of it on a single page. There is no particular advantage. All will get executed on first called first run basis.

?