jQuery $(document).ready () fires twice

90,134

Solution 1

The ready event cannot fire twice. What is more than likely happening is you have code that is moving or manipulating the element that the code is contained within which causes the browser to re-execute the script block.

This can be avoided by including script tags in the <head> or before the closing </body> tag and not using $('body').wrapInner();. using $('body').html($('body').html().replace(...)); has the same effect.

Solution 2

It happened to me also, but I realized that the script had been included twice because of a bad merge.

Solution 3

This happened to me when using KendoUI... invoking a popup window would cause the document.ready event to fire multiple times. The easy solution is to set a global flag so that it only runs once:

var pageInitialized = false;
$(function()
{
    if(pageInitialized) return;
    pageInitialized = true;
    // Put your init logic here.
});

It's sort of hack-ish, but it works.

Solution 4

Make sure you don't include JS file twice. That was my case

Solution 5

You might consider to use

window.onload

instead of

$(document).ready
Share:
90,134
Xenology
Author by

Xenology

Updated on July 05, 2022

Comments

  • Xenology
    Xenology almost 2 years

    I've been sifting around the web trying to find out whats going on here and I have not been able to get a concrete answer.

    I have one $(document).ready on my site that seams to run multiple times regardless of the code that is inside it.

    I've read up on the bug reports for jQuery about how the .ready event will fire twice if you have an exception that occurs within your statement. However even when I have the following code it still runs twice:

    $(document).ready(function() {
        try{    
            console.log('ready');
            }
        catch(e){
            console.log(e);
        }
    });
    

    In the console all I see is "ready" logged twice. Is it possible that another .ready with an exception in it would cause an issue? My understanding was that all .ready tags were independent of each other, but I cannot seem to find where this is coming into play?

    Here is the head block for the site:

    <head>
    <title>${path.title}</title>
    <meta name="Description" content="${path.description}" />
    <link href="${cssHost}${path.pathCss}" rel="stylesheet" type="text/css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript" charset="utf-8"><!----></script>
    <script src="media/js/fancybox/jquery.fancybox.pack.js" type="text/javascript" ><!-- --></script>
    <script src="/media/es/jobsite/js/landing.js" type="text/javascript" ><!-- --></script>
    <script src="/media/es/jobsite/js/functions.js" type="text/javascript"><!-- -->    </script>
    <script src="/media/es/jobsite/js/jobParsing.js" type="text/javascript" charset="utf-8"><!----></script>
    <script src="/media/es/jobsite/js/queryNormilization.js" type="text/javascript" charset="utf-8"><!----></script>
    <script src="${jsHost}/js/jquery/jquery.metadata.js" type="text/javascript" charset="utf-8"><!----></script>
    <script src="${jsHost}/js/jquery/jquery.form.js" type="text/javascript" charset="utf-8"><!----></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js" type="text/javascript" charset="utf-8"><!----></script>
    <script src="${jsHost}/js/jquery.i18n.properties-min.js" type="text/javascript" charset="utf-8"><!----></script>
    
    <script type="text/javascript" charset="utf-8">
    
    function updateBannerLink() {
        var s4 = location.hash.substring(1);
        $("#banner").attr('href','http://INTELATRACKING.ORG/?a=12240&amp;c=29258&amp;s4='+s4+'&amp;s5=^');
    }
    
    </script>
    </head>
    

    Pay no attention to the JSP variables, but as you can see i'm only calling the functions.js file once (which is where the .ready function exists)

  • Xenology
    Xenology almost 12 years
    I'm not using the .wrapInner() tag at all on my site, and as far as i can tell, i have all script tags contained within the <head></head> tags of my site, so i don't see how the code could be getting "rerun" ?
  • Kevin B
    Kevin B almost 12 years
    Where is updateBannerLink being called? if it's in an anchor tag, are you preventing the anchor tag from reloading the page?
  • Kevin B
    Kevin B almost 12 years
    Actually that's a stupid question. Nevermind. If it is happening twice without any interaction from you, the code must be included twice somewhere if the code is in the <head>
  • Xenology
    Xenology almost 12 years
    I wanted to avoid something like this as its messy, and i don't like the idea of having to hack this functionality together. Although this may be the only solution that I have if i can't figure this out
  • qJake
    qJake almost 12 years
    There are some Javascript libraries (like KendoUI) that will cause the document.ready function to execute multiple times on a single page. It's not impossible.
  • Xenology
    Xenology almost 12 years
    The issue here ended up being an IFRAME tag that was included on the page. When removed the document.ready only fired once. As you can see there is an obvious reason as to why the tag is causing a reload on the page <iframe id="pathIframe" frameborder="0" height="600" width="100%" name="path" scrolling="auto" src="#"></iframe>
  • Kevin B
    Kevin B almost 12 years
    Ah, so the iframe was including the parent page as it's src, resulting in the script running twice?
  • Xenology
    Xenology almost 12 years
    Yes, why it wasn't happening in IE i don't know, while this answer was not 100% correct, it lead me to try and find if the page was manipulating the BODY in such a way as to make it load twice, so it set me on the correct path to solving the issue.
  • Inferpse
    Inferpse almost 11 years
    Avoid using src="#" attribute, because it is loading the same page on parent window and inside iframe, that's why it looks like code is called twice. Remove src attribute or set it to "about:blank" to avoid such behavior.
  • sync
    sync over 10 years
    This was a useful answer - I had an element which included a script block which setup an event listener. The container element was being moved in the DOM to somewhere else at DOMReady time, which was binding a second copy of the listener to the event! I wasn't aware that this would happen.
  • Jason FB
    Jason FB almost 10 years
    This was a useful answer for me, I just fixed something that took hours of digging, and turns out that when you use wrapInner() on the $("body") of you page you doc ready will fire twice, causing basically everything jquery does to be double-bound (fun)
  • Darion Badlydone
    Darion Badlydone about 9 years
    In asp.net mvc I missed I had a bundle that included all js of a folder and I created one more for the single file resulting 2 inclusion of the same file
  • balslev
    balslev almost 9 years
    Just wanna say that this worked for me. Working with google maps, somehow my stuff fired twice, but window.onload instead of document.ready worked for me, so thanks.
  • Jeff
    Jeff over 8 years
    Good call! I called my script from a $.getScript from another main script. But I forgot I added a <script> tag to debug!
  • guest271314
    guest271314 almost 8 years
    @KevinB "The ready event cannot fire twice. " See stackoverflow.com/a/36144130
  • Kevin B
    Kevin B almost 8 years
    @guest271314 It can be executed multiple times, and the callback will run every time, however, the event itself only happens once. It cannot trigger again, causing the callback to happen again, which was the point of this answer.
  • leekei
    leekei almost 8 years
    This answer saved me tons of time. I added some initialization code to my JS class so it wont execute the same code twice. Thanks!
  • Prasanna Kumar
    Prasanna Kumar almost 6 years
    I included the same script in both laravel layout and dynamic page. Removing the inclusion in the dynamic php file solved the problem for me.
  • Hexodus
    Hexodus over 4 years
    CSS cannot affect events.
  • Zach Pedigo
    Zach Pedigo over 4 years
    Just wanted to add here, although this is very hacky, it is also incorrect. The syntax should be changed to "if (typeof checkit === 'undefined')." Typeof always returns a string.
  • florieger
    florieger over 4 years
    Thanks for mentioning this. It's quite obvious, but your answer made me double check my includes, which solved the problem ;)
  • RKM
    RKM over 3 years
    Yes the same issue happened to me that accidentally included same script twice.
  • Magno C
    Magno C almost 2 years
    Damn! Happen to me too. Sad but true.