Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  115] [ 4]  / answers: 1 / hits: 41578  / 14 Years ago, thu, april 15, 2010, 12:00:00

Up until now I just put all my jQuery goodness inside the $(document).ready() function, including simple functions used in certain user interactions.



But functions that don´t require the DOM document to be loaded or are only called afterwards anyway, can be placed outside the $(document).ready() as well. Consider for example a very simple validation function such as:



function hexvalidate(color) {
// Validates 3-digit or 6-digit hex color codes
var reg = /^(#)?([0-9a-fA-F]{3})([0-9a-fA-F]{3})?$/;
return reg.test(color);
}


The function is only called from within the $(document).ready() function though.



What is best practice (syntax, speed); placing such a function inside or outside the jquery document ready function?


More From » jquery

 Answers
57

Put it inside so it won't pollute the global namespace. It also ensures a faster resolve of the function name because of JavaScript's scope chains.


Put it outside if it's a reusable component so you could easily move it in a separate file and call from different contexts.


Since you already use JQuery, it's worth mentioning, that in your case you may want to define hexvalidate as a JQuery plugin outside and then invoke it inside.


[#97066] Monday, April 12, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keyonna

Total Points: 521
Total Questions: 104
Total Answers: 96

Location: Samoa
Member since Tue, May 3, 2022
2 Years ago
;