Anyway, there is couple of ways to load external JS file asynchronously or non-blocking way. In this article, we will discuss on by one of them.
defer attribute makes promise to browser. When we are using defer and browser consider this attribute as expected, we should not include any DOM processing JS file in this. The reason is browser will not wait until the file load.
The syntax is like this.
<script src="~/js/js1.js" defer></script>
When browser encounter “defer” it consider the script as parallel loadable object. Now , the question is when defer code will execute ?
In theory, it should happen after the DOM has completely loaded, shortly before the DOMContentLoaded event. In practice, it depends on the OS and browser, whether the script is cached, and what other scripts are doing at the time.
Let us see the loading sequence of async. In this example we are loading four external JS files and the sequence is like this.
Please note than “Raphael-min.js” is loading asynchronously. Here is screen of loading in reality.
We are seeing that “Raphael-min.js” is loading in second position but in sequence, it is in third position. Again, this sequence of loading for some trial, it may vary time to time.