如何异步加载2个Javascript文件并依次运行? [英] How to load 2 Javascript files async and run one after another?

查看:57
本文介绍了如何异步加载2个Javascript文件并依次运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的结构:

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

我需要异步加载两个文件,并在1.js之后运行2.js文件.我该怎么办?

I need to load both files async and run 2.js file after 1.js. How could I do it?

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

If I add async to 2.js they will run at random.

推荐答案

您可以动态添加脚本,以这种方式默认情况下异步加载它们.

You could dynamically add your scripts, in that way they are loaded asynchronously by default.

为确保有序执行,您可以将它们显式标记为非异步.

To ensure an ordered execution you could mark them explicitly as not async.

这是一个最小的例子:

<html>
    <head>
        <script>
            [
                'https://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>

文件1.js包含jquery代码:

The File 1.js contains jquery code:

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

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

In this example the files are loaded asynchrounously but keep the specified order. For further reading you can have a look at: http://www.html5rocks.com/en/tutorials/speed/script-loading/

这篇关于如何异步加载2个Javascript文件并依次运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆