Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); ?

like image 231
IMB Avatar asked Feb 17 '26 13:02

IMB


1 Answers

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>
like image 144
Rob W Avatar answered Feb 19 '26 01:02

Rob W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!