Asynchronous and Deferred JavaScript?
JavaScript is considered a “parser blocking resource”. This means that the parsing of the HTML document itself is blocked by JavaScript. When the parser reaches a <script> tag, whether that be internal or external, it stops to fetch (if it is external) and run it.
This behavior cause issues in page load time, also google consider as an issue. this can be resolve by defer and Asynchronous JavaScript attribute.
Normal execution <script>
Normal execution is the default behavior of the <script> element. The HTML file will be parsed until the script file is hit, at that point parsing will stop and a request will be made to fetch the file (if it’s external). The script will then be executed before parsing is resumed. This will cause slow loading to your webpage.
Take, this example, The script element located somewhere in the middle of the page –
1 2 3 4 5 6 7 8 |
<html> <head> ... </head> <body> ... <script src="function.js"> .... </body> </html> |
The HTML parsing will be paused during the script to be fetched and executed, thereby extending the amount of time it takes to get to first page load.
Deferred execution <script defer>
The defer
attribute tells the browser to only execute the script file once the HTML document has been fully parsed.
In defer execution both parsing and script fetching process run parallel but script execute at the end when parsing is finished.
1 |
<script defer src="function.js"></script> |
Simply put deffer in script tag, A positive effect of this attribute is that the DOM will be available for your script. but since not every browser supports defer yet, you can’t rely on it!
Asynchronous execution <script async>
Asynchronous is the best of both worlds: HTML parsing may continue and the script will be executed as soon as it’s ready. I’d recommend this for scripts such as Google Analytics.
In Asynchronous Execution process parsing and script loading run parallel and script will execute as soon as possible.
1 |
<script async src="function.js"></script> |
The async
attribute is used to indicate to the browser that the script file can be executed asynchronously. The HTML parser does not need to pause at the point it reaches the script tag to fetch and execute, the execution can happen whenever the script becomes ready after being fetched in parallel with the document parsing.
When should I use and what?
Typically you want to use async
where possible for solving page load issue occurs in google test, then defer
then no attribute. Here are some general rules to follow:
- If the script is modular and does not rely on any scripts then use
async
. - If the script relies upon or is relied upon by another script then use
defer
. - If the script is small and is relied upon by an
async
script then use an inlinescript
with no attributes placed above theasync
scripts.
[paypal-donation]