Is there any browser performance difference between defining javascript functions before and after DOM loaded?
I usually define functions after DOM loaded like this
// Example-1 $(document).ready(function(){ function foo(){ alert("foo"); } foo(); });
and some people use this way
// Example-2 function foo(){ alert("foo"); } $(document).ready(function(){ foo(); });
Theory-1: They say Example-1 is slower than Example-2 because Example-1 waited DOM to load then started to define functions and then page became to work in full function. However, in Example-2 functions defined at the same time while DOM is loading so page became full function at the same time when DOM loaded. As a result Example-2 gained some time while Example-1 was trying to define functions.
Theory-2: $(document).ready function itself is slow. To get same result faster use this way
(function() { })();
I couldn’t find anything related to this theories. Could someone explain please what happens behind the scenes?
Thanks.
Advertisement
Answer
After that time I found that defining functions without $(document).ready
is faster. What I couldn’t realise browser already downloaded jQuery library and worked so fast when I am in local. When I go online it starts downloading the library first then define related functions.