jQuery $(document).ready () fires twice

前端 未结 13 833
忘了有多久
忘了有多久 2020-11-29 03:13

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

相关标签:
13条回答
  • 2020-11-29 03:36

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

    0 讨论(0)
  • 2020-11-29 03:37

    There is a possibility to encounter this problem when you add same controller twice in the html.
    For an instance:
    [js]

    app.controller('AppCtrl', function ($scope) {
     $(document).ready(function () {
            alert("Hello");
            //this will call twice 
        });
    });
    

    [html]

    //controller mentioned for the first time
    <md-content ng-controller="AppCtrl">
        //some thing
    </md-content>
    
    //same controller mentioned again 
    <md-content ng-controller="AppCtrl">
        //some thing
    </md-content>
    
    0 讨论(0)
  • 2020-11-29 03:41

    If the iframe doesnt show anything and is used for other reasons (like uploading a file without reload) you can do something like this :

    <iframe id="upload_target" name="upload_target" style="width:0;height:0;border:0px solid #fff;"></iframe>
    

    Notice that src is not included that prevents the second on ready trigger on the document.

    0 讨论(0)
  • 2020-11-29 03:43

    I had a similar issue today. A <button type="submit"> caused the $(document).ready(...) event to fire again in my case. Changing the code to <button type="button"> solved the issue for me.

    See document.ready function called again after submit button? here on stackoverflow for more details.

    0 讨论(0)
  • 2020-11-29 03:44

    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.

    0 讨论(0)
  • 2020-11-29 03:44

    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.

    0 讨论(0)
提交回复
热议问题