14

How do I set the load and execution order of two external async Javascript files?

Given the following...

<script src="framework.js" async></script> // Larger file
<script src="scripts.js" async></script> // Small file

Though second in order scripts.js is downloading and executing before framework.js due to it's file size, but scripts.js is dependent on framework.js.

Is there a way natively to specify the load and execution order whilst still maintaining async properties?

Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
Bradley Flood
  • 10,233
  • 3
  • 46
  • 43

2 Answers2

21

You want to use defer if you want to preserve the execution order. What defer does is it async downloads the script, but defers execution till html parsing is done.

<script src="framework.js" defer></script>
<script src="scripts.js" defer></script>

However, you may want to start creating custom bundles once the number of scripts go higher.

You can see the difference here

Achrome
  • 7,773
  • 14
  • 36
  • 45
3

If you need a solution for IE9 (since it does not support the defer attribute), I have created a small loader script:

https://github.com/mudroljub/js-async-loader

It loads all your scripts asynchronously and then executes them in order.

Community
  • 1
  • 1
Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
  • With all due respect, IE9 does not support the `let` keyword either. Plus, it would be neat if it loaded scripts as soon as they were both available and it was their turn. Instead of having to wait for all scripts to download before executing any. – Samuel Willems Mar 05 '19 at 15:47
  • 1
    You are totally correct and thanks for mention it. I have reverted the code to ES5, which was the original syntax. But it still waits for all the scripts, though. – Damjan Pavlica Mar 06 '19 at 10:05
  • 1
    Haha yea, I suppose simplicity was sort of the strength of this snippet so I get it. – Samuel Willems Mar 07 '19 at 11:03