简体   繁体   中英

How to Dynamically Load Internal Scripts In Order With Javascript

I have several scripts I need to dynamically include in a specific order. I have looked at and tried several answers here: How to include multiple js files using jQuery $.getScript() method

My problem is that the answers here either don't work in my application due to loading the files asynchronously or greatly over complicating the matter due to loading external scripts. The scripts I need to dynamically load are internal. (ie: On my site's server)

In addition to many other attempts, Ive tried:

$.when(
            $.getScript('/1.js'),
            $.getScript('/2.js'),
            $.getScript('/3.js'),
            $.getScript('/4.js'),
            $.getScript('/5.js'),
            $.Deferred(function (deferred) {
                $(deferred.resolve);
            })
        ).done(function() {         
            //Do Something
        });

but this does not load the scripts in proper order and kicks out a slew of errors.

Furthermore, The scripts I need to load are internal and I dont see the need for all the AJAX

Ive also tried other variations to no avail and was hoping someone could illustrate how I could dynamically load internal scripts one after another, preferably without AJAX calls and over complicating?

getScript returns a Promise-like object, so you can await each call of it in a loop for them to be processed in serial:

(async () => {
  for (const path of ['/1.js', '/2.js', '/3.js']) {
    await $.getScript(path);
  }
  // Do something
})()
  .catch((err) => {
    // Something went wrong
  });

For anyone who is using jQuery I have improved @adeneo script so it will load all scripts in the specified order. It doesn't do chain loading, so it's very fast, but if you want even faster, change the 50 ms wait time.

$.getMultiScripts = function(arr, path) {

    function executeInOrder(scr, code, resolve) {
        // if its the first script that should be executed
        if (scr == arr[0]) {
            arr.shift();
            eval(code);
            resolve();
            console.log('executed', scr);
        } else {
            // waiting
            setTimeout(function(){
                executeInOrder(scr, code, resolve);
            }, 50);
        }
    }

    var _arr = $.map(arr, function(scr) {

        return new Promise((resolve) => {
            jQuery.ajax({
                type: "GET",
                url: (path || '') + scr,
                dataType: "text",
                success: function(code) {
                    console.log('loaded  ', scr);
                    executeInOrder(scr, code, resolve);
                },
                cache: true
            });
        });

    });
        
    _arr.push($.Deferred(function( deferred ){
        $( deferred.resolve );
    }));
        
    return $.when.apply($, _arr);
}

How to use:

var script_arr = [
    'myscript1.js', 
    'myscript2.js', 
    'myscript3.js'
];

$.getMultiScripts(script_arr, '/mypath/').done(function() {
    // all scripts loaded
});

In pure js

['/1.js', '/2.js',  '/3.js', '/4.js', '/5.js'].forEach(function(script) {
    var scriptElement = document.createElement("script");
    scriptElement.src = script;

    // append script element where you want (head or body)
    document.head.appendChild(scriptElement);
});

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