Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to control Javascript Async Load Order?

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?

like image 333
Bradley Flood Avatar asked Mar 06 '15 06:03

Bradley Flood


People also ask

How do I load a Javascript file asynchronously?

write before the document has loaded, the script will be executed synchronously as part of loading the page, and will not include any asynchronous callback behavior on its own. If you're creating a script element and adding it to the page, then you'll have access to add event listeners to trigger asynchronously.

Does window onload wait for async scripts?

onload will wait for those asynchronous scripts to finish loading.

What is asynchronous load?

Asynchronous loading means that the code will be processed simultaneously with the rest of the page's content. In other words, the browser will have no downtime while loading a page as it will keep working while waiting for the request to be handled and the code executed in the background.


2 Answers

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

like image 132
Achrome Avatar answered Oct 26 '22 00:10

Achrome


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.

like image 41
Damian Pavlica Avatar answered Oct 26 '22 02:10

Damian Pavlica