Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between document.ready and $function [duplicate]

Possible Duplicate:
What is the difference between these jQuery ready functions?
jquery: Choosing a document.ready method

What is the difference between doing this

$(function() {
    $("a").click(function(event){
        alert("Thanks for visiting!");
    });
});

and this

$(document).ready(function(){
    $("a").click(function(event){
        alert("Thanks for visiting!");
    });
});
like image 791
Matt Morey Avatar asked Feb 22 '12 14:02

Matt Morey


People also ask

What is difference between document ready and document load?

load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.

What does document ready mean?

The document ready event signals that the DOM of the page is now ready, so you can manipulate it without worrying that parts of the DOM has not yet been created. The document ready event fires before all images etc. are loaded, but after the whole DOM itself is ready.

What is the purpose of document ready?

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.

Can I use document ready multiple times?

Yes we can do it as like I did in below example both the $(document). ready will get called, first come first served.


Video Answer


2 Answers

They are the same. Check out the jQuery .ready() docs. Here's a quote from the docs:

All three of the following syntaxes are equivalent:

$(document).ready(handler)

$().ready(handler) (this is not recommended)

$(handler)

like image 69
James Hill Avatar answered Sep 24 '22 20:09

James Hill


There is no difference in functionality between your examples - they both bind to DOM ready.

For reference, there are two points at which you can bind your jQuery code.

The first will execute when the DOM is ready (both are equivalent):

// full example
$(document).ready(function() {
  // code...
});

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

// ES6 example with $ aliased, note this is not supported in IE
jQuery($ => {
  // code...
});

The second will execute when the page has finished loading all images, stylesheets etc.

$(window).on("load", function() {
  // code...
});

The second is useful when you need to get the width() or height() of an image. These properties are only available once the image has completely downloaded to the client system.

Also note that $(window).load(fn); is now deprecated and should no longer be used.

like image 21
Rory McCrossan Avatar answered Sep 24 '22 20:09

Rory McCrossan