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

I have this structure:

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

I need to download both async files and run the 2.js file after 1.js. How can i do this?

If I add async to 2.js, they will execute randomly.

+5
source share
4 answers

You can dynamically add your scripts, so they load asynchronously by default.

To ensure orderly execution, you can explicitly mark them as non-synchronous.

Here is a minimal example:

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

1.js file contains jquery code:

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

In this example, files are downloaded asynchrounously, but retain the specified order. For further reading, you can see: http://www.html5rocks.com/en/tutorials/speed/script-loading/

+4
source

Regular asynchronous scripts do not support loading an order. BTW, ES2015 and above have import syntax for asynchronously loading script files in order:

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

Or you can also use the software API:

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

If you want to use these features today, you should take a look at:

+1
source

One approach would be to download the first file (1.js) asynchronously, and then dynamically add a second script, as indicated in another answer, making it asynchronous.

Download the first file:

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

Then, in the first file, include the following:

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

Hope this helps :)

+1
source

Another way could be to use a different attribute to store the second source content

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

and inside the first script after you finish with the dependent code between the two files (if any), write

 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 

Compared to other solutions, this provides more flexibility when placing a tag anywhere.

0
source

Source: https://habr.com/ru/post/1239710/


All Articles