Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load 2 Javascript files async and run one after another?

I have such structure:

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

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

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

like image 929
thedriveee Avatar asked Jan 03 '16 09:01

thedriveee


1 Answers

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.

Here is a minimum example:

<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>

The File 1.js contains jquery code:

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

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/

like image 115
shock_gone_wild Avatar answered Oct 20 '22 06:10

shock_gone_wild