Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for declaring functions inside jquery ready function

I haven't found a good reference for declaring my own functions inside the

jquery.ready(function(){}); 

I want to declare them so they are inside the same scope of the ready closure. I don't want to clutter the global js namespace so I don't want them declared outside of the ready closure because they will be specific to just the code inside.

So how does one declare such a function...and I'm not referring to a custom jquery extension method/function...just a regular 'ol function that does something trivial say like:

function multiple( a, b ){      return a * b;  } 

I want to follow the jquery recommendation and function declaration syntax. I can get it to work by just declaring a function like the multiply one above...but it doesn't look correct to me for some reason so I guess I just need some guidance.

like image 298
Ralph Caraveo Avatar asked Feb 25 '09 21:02

Ralph Caraveo


People also ask

Can we write function inside function in jQuery?

Yes, you can.

Can we write function inside document ready?

Yes, you can do that, it's just a matter of scope. If you only need to access callMe() from within $(document). ready(function() { }) , then it's fine to put the function there, and offers some architecture benefits because you can't access the function outside of that context.

What is difference between $( document .ready function () vs $( function ()?

So technically they are both the same. Not major difference between these two declaration. They used based on weather you use JavaScript then you should use $(document). ready declaration in other case you use jQuery library which is a part of JavaScript then you should use $(function) declaration.

Can there be more than one ready function in jQuery?

Yes we can do it as like I did in below example both the $(document). ready will get called, first come first served.


1 Answers

I believe that you would be okay just declaring the function inside the ready() closure, but here you can be a bit more explicit about the local scoping:

jQuery.ready(function() {       var myFunc = function() {             // do some stuff here       };       myFunc();   }); 
like image 124
jonstjohn Avatar answered Oct 07 '22 00:10

jonstjohn