There are actually two ways we can bypass the problem of the blocking script — async
and defer
.<br/>jquery
Async scripts will download the script without blocking rendering the page and will execute it as soon as the script finishes downloading.<br/>app
You get no guarantee that scripts will run in any specific order, only that they will not stop the rest of the page from displaying. <br/>async
It is best to use async
when the scripts in the page run independently from each other and depend on no other script on the page.<br/>this
For example, if you have the following script elements:rest
<script async src="js/vendor/jquery.js"></script> <script async src="js/script2.js"></script> <script async src="js/script3.js"></script>
You can't rely on the order the scripts will load in. jquery.js
may load before or after script2.js
and script3.js
and if this is the case, any functions in those scripts depending on jquery
will produce an error because jquery
will not be defined at the time the script runs.<br/>code
Defer will run the scripts in the order they appear in the page and execute them as soon as the script and content are downloaded:<br/>ip
<script defer src="js/vendor/jquery.js"></script> <script defer src="js/script2.js"></script> <script defer src="js/script3.js"></script>
All the scripts with the defer
attribute will load in the order they appear on the page.<br/>ci
So in the second example, we can be sure that jquery.js
will load before script2.js
and script3.js
and that script2.js
will load before script3.js
.<br/>element
async
.<br/>