如何加载2个Javascript文件异步并一个接一个地运行?

问题描述 投票:5回答:5

我有这样的结构:

<script src="/Content/Scripts/1.js"></script>
<script async src="/Content/Scripts/2.js"></script>

我需要在1.js之后加载两个文件async并运行2.js文件。我怎么能这样做?

如果我将async添加到2.js,它们将随机运行。

javascript html asynchronous
5个回答
6
投票

您可以动态添加脚本,默认情况下它们是异步加载的。

为确保有序执行,您可以将它们明确标记为非同步。

这是一个最小的例子:

<html>
    <head>
        <script>
            [
                'http://code.jquery.com/jquery-1.11.3.min.js',
                '1.js'
            ].forEach(function(src) {
                var script = document.createElement('script');
                script.src = src;
                script.async = false;
                document.head.appendChild(script);
            });
        </script>
    </head>
    <body>

    </body>
</html>

File 1.js包含jquery代码:

$("body").append("<div>It works</div>");

在此示例中,文件是异步加载的,但保持指定的顺序。如需进一步阅读,请查看:http://www.html5rocks.com/en/tutorials/speed/script-loading/


1
投票

常规异步脚本不支持加载顺序。 BTW,ES2015及更高版本具有import语法,可按顺序异步加载脚本文件:

import x from "x.js";
import y from "y.js";

或者您也可以使用编程API:

Promise.all([System.import("x.js"), System.import("y.js")]).then(() => {
   // Do stuff once they've been already loaded...
});

如果你想今天使用这些功能,你应该看看:


1
投票

一种方法是异步加载第一个文件(1.js),然后通过使其异步加载,动态添加另一个答案中提到的第二个脚本。

加载第一个文件:

<script async src="/Content/Scripts/1.js"></script>

然后在第一个文件中,在底部包含以下内容,

var script = document.createElement('script');
script.src = "/Content/Scripts/2.js";
script.async = true;
document.head.appendChild(script);

希望这可以帮助 :)


1
投票

另一种方法是使用另一个属性来存储第二个源内容

<script async src="/Content/Scripts/1.js"></script>
<script id="second" async data-src="/Content/Scripts/2.js"></script>

在完成2个文件(如果有的话)之间的相关代码之后,在第一个脚本内部写入

var script = document.getElementById('second');
script.setAttribute("src",script.getAttribute("data-src"));
script.removeAttribute("data-src"); //Totally upto you if you want to remove it

与其他解决方案相比,这为您在任何地方放置标签提供了更大的灵活性。


0
投票

从“Abhishek singh”开始 - 我的回答是我自己创建了一些代码片段。

您可以根据需要连续执行多个js文件。

HTML看起来像这样:

<title>Script execution sequence</title>
<body>

    <script async data-ascript-id='2' data-src='second.js'></script>
    <script async data-ascript-id='1' data-src='first.js'></script>

    <script async src="pixel.js"></script>

</body>

pixel.js:

console.log("Pixel script executed");

var aon_scripts = document.querySelectorAll('[data-ascript-id]');

if(aon_scripts.length > 0){

    var next_script = document.querySelectorAll('[data-ascript-id="1"]')[0];

    console.log("pixel.js found next script");

    next_script.setAttribute("src", next_script.getAttribute("data-src") );
}

first.js:

console.log("Next script executed");

var current_script = document.currentScript;

var this_script_data_id = current_script.getAttribute("data-ascript-id");

if(aon_scripts.length > parseInt(this_script_data_id) ){

    console.log("There is more script");

    var next_script = document.querySelectorAll('[data-ascript-id="'+                
(parseInt(this_script_data_id) + 1) +'"]')[0];

    next_script.setAttribute("src", next_script.getAttribute("data-src") );

}
else{

    console.log("No more scripts to execute");

}

second.js和那里的所有代码都与first.js相同。

当我有first.js和second.js时输出相同:

pixel.js:      Pixel script executed
pixel.js:11    pixel.js found next script
first.js:1     Next script executed
first.js:9     There is more script
second.js:1    Next script executed
second.js:18   No more scripts to execute

如果有人想要详细解释,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.