IMB
IMB

Reputation: 15919

Jquery ready() vs simple function call before </body>

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

Answers (1)

Rob W
Rob W

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>


When you don't wrap the function call in a wrapper, both approaches have a similar result:

<script>
$(myfunc);
</script></body>

</bodY><script>
myfunc();
</script>

Upvotes: 4

Related Questions