There are three ways of using The Script tag in the HTML document
In a real/live project, the Performance of any application matters a lot. So efficient script loading is also a good factor for a performant application. So I will discuss all three ways of script use and will conclude with the Best Way of using the script in a document.
Regular — In a Regular way, Mostly we use the script tag in the Body section at last. Because if we use it in the Head section, then HTML parsing will stop once the script tag comes in the picture, and once the whole script gets executed then HTML Parsing will resume. So the time taken for DomContentLoaded Event will higher. The problem with this approach is, it does not make parallel requests to fetch the individual files. So the time taken for DomContentLoaded Event will higher.
Using Async/Defer -Makes parallel requests to fetch the individual files. So the time taken for DomContentLoaded Event will less than the Regular way. So, using the script with async/defer attribute is a good idea. But there are use cases and differences for using async/defer attribute.
Similarities between Async and Defer approach
Makes parallel requests to fetch the individual files.
Differences between Async and Defer approach
Async- Scripts are fetched asynchronously and executed immediately.
Defer- Scripts are fetched asynchronously and executed after the whole HTML parsing.
Async- DomContentLoaded Event will not wait for async scripts execution
Defer- DomContentLoaded Event will wait for defer scripts execution
Async- Scripts Execution order is not Guaranteed
Defer- Scripts Execution order is Guaranteed
Async- Mostly used when order is not important like 3rd party libs.
Defer- It is the best solution, Mostly used when execution order matters.