PageSpeed OptiPic — автоматическая оптимизация сайта для требований Google Pagespeed Insights
JavaScript: Слияние, сжатие, ленивая загрузка. CSS: Сжатие размера и оптимизация загрузки. Оптимизация изображений. Оптимизация сторонних виджетов и систем аналитики.

Что лучше - иметь 100 готовых к документу или 1 готовых к документу?

Просто интересно, влияет ли количество вызовов document.ready на скорость загрузки страницы. Есть ли способ в Gulp / Grunt уменьшить/обфусцировать JS, удалив отдельные функции 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

Много вызовов готовности документа не должны сильно влиять на производительность приложения. Лучшим решением может быть иметь только один и инициализировать все, что вам нужно, там. Однако это зависит от структуры вашего приложения, и вы должны чувствовать себя комфортно, имея больше одного. В любом случае, я не думаю, что есть какая-либо задача Gulp, которая объединяет различные готовые функции в одну, потому что она будет затрагивать логику приложения.

#3

Вы можете иметь несколько таких, но это не всегда самое аккуратное решение. Постарайтесь не злоупотреблять ими, так как это серьезно сказывается на читаемости. Кроме того, стоит отметить, что функция, определенная внутри одного блока $(document).ready, не может быть вызвана из другого блока $(document).ready.

$(document).ready(function() { alert('hello1'); function saySomething() { alert('something'); } saySomething(); }); $(document).ready(function() { alert('hello2'); saySomething(); }); 

вывод был

hello1 something hello2 

Проверьте этот пост и этот

#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.

?