Proper use of jquery $(document).ready() when declaring functions called within ready()
I have gotten into the habit of starting jquery coding with the ready function $(function(){...});
and putting all functions called from ready within ready.
Then I realized that some of the functions put into the ready function probably didn't need to be there.
For example, simple functions used by events in document ready could be declared outside of it:
function checkEmail(objelement){
var emailRx = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
return emailRx.test(objelement.val()) ? true : false;
}
Then used inside of it:
//code snippet for example
$(function(){
$("form[name='contactform']").submit(function(){
$("input[type=text]").each(function(){
if($(this).attr("id") == "email" && !checkEmail($(this))) {
$(this).prev().c开发者_JAVA技巧ss("color","red");
}
});
});
});
I searched through many SO previous questions and couldn't seem to find an answer.
Is it better, worse, or no different to declare functions outside of ready in this manner?
If you declare them outside, all it means is that they exist in the global scope.
An advantage of this is that they can be reused outside of the document.ready function. A disadvantage is that they clutter up the global namespace (this can be avoiding by namespacing, if you want).
Personally, if I'm going to reuse them, they go outside. If they need to reference a variable or something else that will only exist within the scope of my domready handler, they go inside (usually as anonymous functions though).
Lately, I've been putting everything I can outside of the domready handler simply because the interpreter has to parse all function declarations within the domready handler before starting to execute the handler and delaying execution of your domready handler sort of defeats the purpose (regardless of how negligible that time is).
Better
Your code will be easier to read.
Remember $(document).ready()
is just a function too.
Anything that can be packaged up and put in a potentially reusable function call should be.
Think of it this way... would you do the same if you were dealing with a button's click event?
functions should always be declared outside the ready or any load event. But you should make sure that the functions are declared before you use them in order to avoid any error in the code execution.
精彩评论