Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between $(document).ready() and including a script at the end of the body?

What's the difference between executing a JavaScript function on jQuery's $(document).ready() and including it in the HTML in script tags at the end of the body?

Thanks,

DLiKS

like image 692
DLiKS Avatar asked Dec 21 '22 18:12

DLiKS


2 Answers

JavaScript code inside the <script> tags is evaluated (executed) immediately. Note that in this case the page has not been parsed yet (entirely), and the DOM is not yet ready.

JavaScript code inside the jQuery ready() callback is evaluated on the DOMContentLoaded event, which occurs after the entire HTML source code has been parsed by the browser.
About this event: https://developer.mozilla.org/en/Gecko-Specific_DOM_Events

Note that the modern way of defining the ready handler is this:

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

Also, check out this SO question, which points out what happens when you don't use the ready callback: How many JavaScript programs are executed for a single web-page in the browser?

like image 130
Šime Vidas Avatar answered Apr 27 '23 01:04

Šime Vidas


  • A script at the end of the body will run as soon as it is loaded.
  • $.ready is executed after the document is complete (any linked css is also loaded).
  • Body.load runs only when all images are loaded as well.
like image 20
GolezTrol Avatar answered Apr 27 '23 01:04

GolezTrol