Be the first user to complete this post
|
Add to List |
Difference between async and defer attributes in script tags
Lately you might have come across script tags in your html documents with the async
and/or defer
attributes. In this article, we will explain these terms so that you can decide when to use it in your application.
NOTE: Consider checking browser support before using these features in your application.
Lets start with a regular script tag having no attributes.
<script src="myfile.js"></script>
When the browser comes across the above line in your markup, this is what happens.
- Pause parsing the document.
- Make a request to fetch the file.
- Execute the script after it has been downloaded.
- Resume parsing the document.
async
attribute is for.
Async
When you add theasync
attribute to your script tag, the following will happen.
<script src="myfile1.js" async></script>
<script src="myfile2.js" async></script>
- Make parallel requests to fetch the files.
- Continue parsing the document as if it was never interrupted.
- Execute the individual scripts the moment the files are downloaded.
NOTE: Scripts that you programmatically insert into the DOM are async by default, unless you explicitly set their async attribute to false at insertion time.
Defer
Defer is very similar to async with one major differerence. Here's what happens when a browser encounters a script with the defer attribute.<script src="myfile1.js" defer></script>
<script src="myfile2.js" defer></script>
- Make parallel requests to fetch the individual files.
- Continue parsing the document as if it was never interrupted.
- Finish parsing the document even if the script files have downloaded.
- Execute each script in the order they were encountered in the document.
defer
is pretty much what you want to do in your files. However, due to limited browser support, its not a viable option at the time of writing.
NOTE: The async and defer attributes are ignored for scripts having no src
attribute.
Until we live in a better world, the good ol' technique of placing scripts at the bottom of your document should work just fine for scripts that are dependednt on each other. As discussed earlier, the best use case for using the
async
attribute in scripts is for external scripts that are completely self contained.
Also Read:
- Pure vs Impure functions
- Default function parameters
- window vs document
- Generators and Yield in es6
- Why use javascript strict mode