0

From one man who currently works on Google I saw code which looks similar to this:

$(document).bind('ready load', function() { ... });

There are 2 intertwined questions:

  • Since I'm only novice in JS, I don't understand the purpose of this binding. Why we need both ready and load? I tend to think that sometimes we need ready, sometimes load, but not both.

  • Also, I tend to think that ready is for document, and load is for window. That's mean:

    $(document).ready(function() { ... });
    $(window).load(function() { ... });
    

    But from the first snippet, it could be seen, that both ready and load are used for document. So, my assumption (ready is for document, and load is for window) isn't correct?

john c. j.
  • 725
  • 5
  • 28
  • 81
  • 1
    That code is over 7 years old now and is currently out of date. At the time I believe it was valid, though. You're correct in that `ready` fires on the document and `load` on the window, however following current practices it should be `$(window).on('load', fn)` as the `load()` function is no longer an event handler (it retrieves content via AJAX) – Rory McCrossan Jan 29 '18 at 08:47
  • @RoryMcCrossan Thank you very much. Also, what you think about trying to bind `ready` and `load`? Is there any benefit from it, based on your views and modern jQuery? – john c. j. Jan 29 '18 at 09:35
  • 1
    Assuming you mean binding to the same element, then no, there is no benefit. If you want to bind `load` and `ready` to the `window` and `document` separately, then yes, there is a benefit there if you need to execute logic after the window has loaded. – Rory McCrossan Jan 29 '18 at 09:35

1 Answers1

0

The major difference between ready and load i think is the one below:

  • ready fires when the dom is ready, this means that the elements hierarchy is ready, even if the content (i.e an image still loading) has not yet finished completely. It is safe to handle the DOM at this stage.
  • load fires when even the content has finished loading for a given element $(smthing).load. This means that if attached to the document, this event will fire after all content is loaded (i.e images finished downloading etc )

EDIT: Also take a look here jQuery - What are differences between $(document).ready and $(window).load?

MKougiouris
  • 2,821
  • 1
  • 16
  • 19
  • 1
    This isn't quite accurate as the `load` event only fires on the `window`, not the `document`, `img`, `script` and frames. – Rory McCrossan Jan 29 '18 at 08:50
  • 1
    @MKougiouris Thanks for answer and for useful link, but from my point of view, you missed the point of my post a bit. Yes, I know about the difference between `ready` and `load` - it was clearly stated in my post. The question was about binding and about `load` binded to `document`. Rory McCrossan's comment ("That code is over 7 years old...") is much closer to what I'm asked for. – john c. j. Jan 29 '18 at 08:59