简体   繁体   中英

Load multiple JS files with the given order using jQuery $.getScript() method

I have loaded jQuery first & tried to load some js files using the below method

Note: " daterangepicker.js " require " moment.js "

$.when(
    $.getScript("https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"),
    $.getScript("https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.js"),
    $.getScript("1.js"),
    $.getScript("2.js"),
    $.getScript("3.js"),
    $.Deferred(function(deferred) {
        $(deferred.resolve);
    })
).done(function() {
    $('input[name=\'time\']').daterangepicker();
});

But i got an error

Uncaught TypeError: moment is not a function

在此处输入图片说明

Then i have tried the second method.

$.when(
    $.getScript("https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js").done(function() {
        $.getScript("https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.js").done(function() {
            alert("scripts loaded");
        });
    }),
    $.getScript("1.js"),
    $.getScript("2.js"),
    $.getScript("3.js"),
    $.Deferred(function(deferred) {
        $(deferred.resolve);
    })
).done(function() {
    alert("All js files are loaded");
    $('input[name=\'time\']').daterangepicker();
});

This time i got

daterangepicker is not a function

在此处输入图片说明

Because " All js files are loaded" alert is coming first & "scripts loaded" alert is coming second.

I have implemented a new logic

function getScripts(scripts, callback, i) {
    i = i ? i : 0;
    $.getScript(scripts[i]).done(function() {
        ++i === scripts.length ? callback() : getScripts(scripts, callback, i);
    });
}

getScripts(
    [
        "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js",
        "https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.js",
        "1.js",
        "2.js",
        "3.js"
    ],
    function() {
        alert("all files are loaded");
        $('input[name=\'time\']').daterangepicker();
    });

Its working as expected.

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