简体   繁体   English

等待 Javascript 加载 Promise

[英]Waiting Until Javascript Loads With A Promise

I am building a solution in which multiple Javascript libraries are dynamically loaded onto the screen at different points in time based on the user's interaction.我正在构建一个解决方案,其中多个 Javascript 库根据用户的交互在不同时间点动态加载到屏幕上。 After the libraries are loaded, the scripts in the library are executed.加载库后,将执行库中的脚本。

For example:例如:

    let script1 = '<script class="'+script_class+'" id="' + script_id + '" type="text/javascript" src="' + some_script_url +'"></script>';
    
     $("head").append(script1);

let script2 = '<script class="'+script_class+'" id="' + script_id + '" type="text/javascript" src="' + some_script_url +'"></script>';
    
     $("head").append(script2);

let script3 = '<script class="'+script_class+'" id="' + script_id + '" type="text/javascript" src="' + some_script_url +'"></script>';
    
     $("head").append(script3);

And then a function will execute a function inside the script:然后 function 将在脚本中执行 function :

function doSomething() {
      scriptFunction();
}

doSomething();

The problem is sometimes the script will not fully be loaded before the function tries execute.问题是有时在 function 尝试执行之前脚本不会完全加载。 This causes error likes "scriptFunction not found".这会导致错误,例如“未找到 scriptFunction”。 How can I wait for each libraries to load before executing the scripting?在执行脚本之前如何等待每个库加载? Can this be done with promises?这可以通过承诺来完成吗?

Here is a function that returns a promise that resolves when a script has loaded:这是一个 function ,它返回一个 promise ,它在脚本加载时解析:

 function loadScript(src) { return new Promise(resolve => { const script = document.createElement("script"); script.setAttribute("async", ""); script.onload = resolve; script.setAttribute("src", src); document.head.appendChild(script); }); } const urls = [ "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js", "https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js" ]; Promise.all(urls.map(loadScript)).then(ready); function ready() { console.log("all loaded"); console.log($.fn.jquery); console.log(luxon.DateTime.now().toString()); }

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

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