Any way to control Javascript Async Load Order?

2019-04-28 08:46发布

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?

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-04-28 08:58

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

查看更多
时光不老,我们不散
3楼-- · 2019-04-28 09:15

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

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

In short, it loads all your scripts asynchronously, and then executes them consequently.

查看更多
登录 后发表回答