简体   繁体   English

如何使用 Javascript 按顺序动态加载内部脚本

[英]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我在这里查看并尝试了几个答案: 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此外,我需要加载的脚本是内部的,我认为不需要所有 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?我也尝试过其他变体但无济于事,希望有人能说明我如何一个接一个地动态加载内部脚本,最好是没有 AJAX 调用和过于复杂?

getScript returns a Promise-like object, so you can await each call of it in a loop for them to be processed in serial: getScript返回一个类似 Promise 的对象,因此您可以在循环中await它的每次调用,以便它们以串行方式进行处理:

(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.对于使用 jQuery 的任何人,我都改进了 @adeneo 脚本,因此它将按指定顺序加载所有脚本。 It doesn't do chain loading, so it's very fast, but if you want even faster, change the 50 ms wait time.它不进行链式加载,因此速度非常快,但如果您想要更快,请更改 50 毫秒的等待时间。

$.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在纯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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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