2

What is the advantage of using $(document).ready(my_function) instead call my_function() in the bottom of my html script?

VSHenrique
  • 45
  • 4
  • 1
    `$(document).ready(my_function)` waits for your whole page to load before calling the function, it is safer if your page takes time to load. –  Nov 10 '17 at 12:18
  • 2
    Exact duplicate of https://stackoverflow.com/questions/6026645/document-readyfunction-vs-script-at-the-bottom-of-page – Makarand Patil Nov 10 '17 at 12:20
  • obviously they are not the same thing: the scope for example.. – neoDev Nov 10 '17 at 12:23
  • 1
    Why are duplicate questions up-voted? You will get the exact similar question if even small effort is made to search it – Makarand Patil Nov 10 '17 at 12:23

2 Answers2

2

They both do the same thing.

$(document).ready(function() { // code }); allows you to run the javascript once the page onload function has been called. This is the same as running it once the DOM has loaded by calling it at the end of your HTML.

ConorReidd
  • 276
  • 5
  • 25
1

Only if you put the function at the very bottom of the page, there is no advantage. However, you usually want to have the choice to put code where you like it. $(document).ready() gives you this choice (actually the underlying javascript does).

Furthermore, for other programmers, it might not seem obvious that this function has to be executed right away when the page loads, and might therefor refactor the function somewhere else unknowingly. By using the document ready event, you're making your code more explicit i.e. saying "this piece of code needs to run as soon as the document has been loaded".

Glubus
  • 2,819
  • 1
  • 12
  • 26