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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With