Reputation: 15919
If I'm calling my JS scripts just before the closing body tag, is there a difference between using jQuery ready function like $(myfunc());
vs just using simply myfunc();
?
Upvotes: 3
Views: 374
Reputation: 349232
Only one difference would exist:
When you use $(function(){...})
(short for$(document).ready(function(){...})
, you're automatically wrapping the code in an anonymous function, thus creating a private scope. Variables defined using var
inside this scope aren't leaked to the global scope.
<script>
$(function(){ //<-- Anonymous function wrapper
var test = 1; //"Private" variable
alert(test); //Alert: 1
});
alert(window.test); //Nothing
</script>
<body>
Versus
<script>
var test = 1;
alert(test); //Alert: 1
alert(window.test); //Alert: 1
</script>
</body>
<script>
$(myfunc);
</script></body>
</bodY><script>
myfunc();
</script>
Upvotes: 4