Javascript includes not loading for later in the page

前端 未结 7 2631
我寻月下人不归
我寻月下人不归 2021-02-20 08:42

We have a Rails application where we are including our application dependencies in the html head within application.js:

//= require jquery
//= requi         


        
7条回答
  •  盖世英雄少女心
    2021-02-20 08:52

    This code will load each script URL put in libs in the exact order, waiting for one to fully load before adding the next one. It's not as optimised than letting the browser doing it, but it allow you to monitor the errors and force the order of the loading.

    (function(){
        var libs = [
            "http://example.com/jquery.js",
            "http://example.com/tracker.js",
            "http://example.com/myscript.js"
        ];
        var handle_error = function() {
            console.log("unable to load:", this.src);
        };
        var load_next_lib = function() {
            if(libs.length) {
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = libs.shift();
                script.addEventListener("load", load_next_lib);
                script.addEventListener("error", handle_error);
                document.body.appendChild(script);
            }
        };
        load_next_lib();
    })();
    

    But I would advise you to check every

提交回复
热议问题