javascript – $(document).ready getting called twice? Here’s why.

by Matt Daum

Recently 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: , ,

4 Responses to “javascript – $(document).ready getting called twice? Here’s why.”

  1. Shanimal Says:

    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.

  2. guillaume Says:

    I love you !
    I can have my week end now !

  3. Jesse Says:

    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..

  4. Ashish Datta Says:

    Jesse, you could run an un-minified version of jQuery and place a breakpoint inside the ready() function.

Leave a Reply