ZILONG PAN
ZILONG PAN

Reputation: 8035

why add this $(function () { at the first line of the javascript file?

$(function () {
 console.log('hello');
 //...
})

I saw the code like this. Don't know the purpose of adding the first line (function)? Could Someone explain this?

Upvotes: 0

Views: 266

Answers (2)

Koby Douek
Koby Douek

Reputation: 16693

Wrapping you Javascript code with $(function () {:

$(function () {
    console.log( "ready!" );
});

is the same (a Shorthand version) as writing:

$(document).ready(function() {
    console.log( "ready!" );
});

Which ensures the script will only run once the page Document Object Model (DOM) is ready for Javascript code to execute (Jquery docs).

Upvotes: 1

varman
varman

Reputation: 8894

That is just jQuery short-hand for

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

Upvotes: 1

Related Questions