When a script is loaded, it loads in blocking or synchronous mode, which means that the browser waits for the script to finish loading before executing any code after it.
So in this case,
script2.js cannot start loading before
script1.js finishes loading -
<body> <script src="script1.js"> </script> <script src="script2.js"> </script> </body>
As you can imagine, this becomes problematic when -
script2needs variables that are in
script1is really huge, and the entire page needs to wait for the script to finish loading.
The browser waits for the script to finish because it assumes that the script may have code that may update the page contents using
document.write. If your script isn't using
document.write, then waiting for the browser to finish loading isn't useful.
In order to get past this, there are two attributes that can be used -
defer: defer tells browser that script wont generate any document content and can safely be downloaded without blocking the page and this script should be deferred until all the page is downloaded. defer is executed only when the page is completely parsed.
asyncis similar to defer in the sense that it won't change anything in the DOM, but unlike defer, async scripts are executed as soon as they are downloaded. This is advantageous because scripts can potentially execute sooner.
<script defer src="script1.js"> </script> <script async src="script2.js"> </script>
Blocking scripts can slow down page. Use
async to limit effects of blocking script.
async scripts must not modify page content using
defer: defer is executed only when the page is completely parsed.
async: async scripts are executed as soon as they are downloaded