javascript – $(document).ready getting called twice? Here’s why.
by Matt DaumRecently we found ourselves having a really weird problem on a project: Every time a page was loaded it seemed a bunch of different Javascript functions were being called multiple times and making many widgets on the page break and we couldn’t figure it out. Some of the functions were our own code, some part of the package we were using. After a while we narrowed it down to that all the functions in the
$(document).ready(...);
we’re being called twice. We had never seen this. After about an hour of removing javascript files and just headbanging, and many thanks to Ashish, we found the root cause. We had written in a quick hack for a late proof of concept to string replace on the entire HTML of a page a specific string. We did it this way:
$('body').html($('body').html().replace(/{REPLACETEXT}/i, "More important text"));
Basically we used a regex to parse the entire HTML tree and then replace it with the updated text. Unknowingly this caused the document ready event to be triggered again(though now it makes sense), causing many widgets to get extra HTML.
Let this save you some headbanging.
Tags: bugs, javascript, jQuery

November 15th, 2010 at 10:50 pm
I noticed too that if there is an error in the ready(function(){ it fails silently and causes the function to run again? At least that was my experience.
March 18th, 2011 at 1:26 pm
I love you !
I can have my week end now !
October 19th, 2011 at 11:32 pm
Wow! That was my problem to! Though can’t locate just yet where it is getting triggered from.. Need better stack information… I’m sure it will rear its ugly head soon..
October 31st, 2011 at 10:42 pm
Jesse, you could run an un-minified version of jQuery and place a breakpoint inside the ready() function.