bjkeefe
bjkeefe

Reputation: 71

Difference between different document ready handlers

N00b here. Apologies in advance if this is a bad question.

What's the difference, in effect, between these two jQuery declarations, if any?

$(document).ready(function(){
    alert("I'm so loaded 1.");
});

and

$('document').ready(function(){
    alert("I'm so loaded 2.");
});

On a related note, why does this work ...

$(document).on('ready',function() {
    alert("I'm so loaded 3.");
});

... but this doesn't?

$('document').on('ready',function() {
    alert("I'm so loaded 4.");
});

Upvotes: 1

Views: 126

Answers (2)

martincarlin87
martincarlin87

Reputation: 11062

I've never seen it used as

$('document').ready(function(){
    alert("I'm so loaded 2.");
});

before and gathering from bjkeefe's comment and Kevin B's answer, it's not valid.

$(document).ready(function(){
    alert("I'm so loaded 1.");
});

Means once the page is fully loaded, execute the function. This is useful because then no jQuery will try to execute while the page is still loading and the particular element isn't loaded yet.

$(document).on('ready',function() {
    alert("I'm so loaded 3.");
});

The on function means that any events applied to a dynamically create element will still work as normal but I've never used on in this way before though so I can't guarantee that it would work in this scenario, I usually use on with something like click, hover etc. as what it does is make sure that any jQuery applied to dynamically created elements (elements created after the page has been loaded) will still work as without on, the jQuery would work on elements contained within the document normally but not on dynamically generated elements.

Upvotes: -1

Kevin B
Kevin B

Reputation: 95056

The .ready method ignores the passed in selector because the only valid object it can be called on is the document. It isn't recommended to use .on or .bind with the ready event. Also, you should never use 'document' because document is always available to you directly.

Upvotes: 5

Related Questions