简体   繁体   中英

Does jquery $document.ready wait for json files to be loaded?

I get HTML configuration data from a json file. When that has loaded, I need to make sure that the document is ready before plugging the HTML into existing elements.

    var cfg;
    function getJSONconfigdata() {
        $.getJSON("/quizdata.json", function (json) {
            cfg = json;          
            //Now do everything else
            init();
        });
    }
    getJSONconfigdata()

    function init(){
        //Plug cfg values into existing dom elements. but they may not exist yet.
        //...
    }

init() is called after the json file has been parsed, but how do I make sure the dom is also ready? I have tried $(function (){ init(); }); but cant make it work - it seems to fire before json is loaded.

Yes, the $(document).ready() runs when the DOM is prepared for JS. When many people use jQuery they will put all of their code that will interact with page elements within the $(document).ready() statement to ensure that. So

$( document ).ready(function() {
    var cfg;
    function getJSONconfigdata() {
        $.getJSON("/quizdata.json", function (json) {
            cfg = json;          
            //Now do everything else
            init();
        });
    }
    getJSONconfigdata()
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM