Is having 100 document ready better or worse than 1 document ready?
Asked Answered
E

4

11

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

Eyecatching answered 30/8, 2016 at 9:32 Comment(5)
Why do you want multiple document.ready ?Opsonize
Please show your code, maybe it will allow people to help you with your problemExoergic
@Leopard, there are always many of them. For example, almost any script uses one for its own perposes.Kolomna
@Leopard OP might be asking the question because he might be thinking about refactoring his existing code base to just have all his scripts fire of off a single document ready.Geisel
The things people think will severely affect their code performance and the things that will severely affect their code performance never seem to be related...Sear
K
19

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

Kolomna answered 30/8, 2016 at 9:40 Comment(6)
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')?Proposition
@Thomas, updated answer with answer on your question.Kolomna
For IE 11: 2469ms, 288ms, 1361ms and 321ms. There is a significant difference there. Well... in those cases where you have 1000 document ready scripts with little runtime of the function itself, in which case: what the hell are you doing? In any other case, that 2.4ms overhead is not going to make a difference for one function run on document ready.Janessa
@Thomas, document.ready in jQuery is actually a promise that gets resolved as soon as document.readyState === 'complete' can be detected. The DOMContentLoaded event is one of the signals for checking the status of document.readyState.Segal
@Sumurai8, checked in IE11 (Win 7) - there is no any difference between both jQuery ways at all. Are you sure 3rd script was not the first you ran on the page? About the first one - yes, it takes 2 seconds there.Kolomna
I may not have had that jquery version in my cache at that point. Either that, or the cloud server on which this machine runs had some trouble loading a very simple page. It now also returns a low number.Janessa
D
4

Many document ready calls shouldn't affect much the application performance. The best solution may be having only one and init there all you need. But it depends on your application structure and you should be more confortable having more than one. Anyway, I don't think there is any Gulp task that wraps different ready functions in one, because it will touch the application logic.

Diao answered 30/8, 2016 at 9:36 Comment(0)
T
4

You can have multiple ones, but it's not always the neatest thing to do. Try not to overuse them, as it will seriously affect readability. Other than that , it's perfectly legal.

It's also worth noting that a function defined within one $(document).ready block cannot be called from another $(document).ready block.

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

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

output was

hello1
something
hello2

Check this post and this one

Tia answered 30/8, 2016 at 9:38 Comment(1)
More detailed answer: #1328256Oestriol
T
2

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.

Tilney answered 30/8, 2016 at 9:42 Comment(2)
The bottom of your answer is contained in a blockquote, but there's no link to the source of the quote. Is it actually quoting from something? If so, please identify the source. If not (i.e. it's your own words), please remove the blockquote markdown so it's not displayed as one.Meloniemelony
@AnthonyGrist, removed quote as my own words, so please remove down vote.Tilney

© 2022 - 2024 — McMap. All rights reserved.