Magento 2 script tag and available options in layout xml
- Bilal Malik
- Aug 22, 2020
- 1 min read
We can add a script via layout XML file in Magento 2.
The below format will stop the HTML parse until js downloaded and executed.
<script src="Bilal_Usean/js/sample.min.js" />
The below format will stop the HTML parse only on while executing js.
<script src="Bilal_Usean/js/sample.min.js" async="async" />
The below format will not stop the HTML parse, it will execute js after HTML parser completed.
<script src="Bilal_Usean/js/sample.min.js" defer="true"/>
Defer Vs Sync
If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)
If async is not present and defer is present: The script is executed when the page has finished parsing
If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page
Below picture clearly displays the difference between the async and defer ( I took it from here thanks for this author)

We can call the URL type of script as below.
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" src_type="url" />
We can set charset, ie_condition.
<script src="Bilal_Usean/js/sample.min.js" charset="UTF-8" />
<script src="Bilal_Usean/js/sample.min.js" ie_condition="IE 9" />
Default script type is type="text/javascript" and we can change what we need
<script src="Bilal_Usean/js/sample.min.js" type="text/javascript" />
I hope it helps. If you need any clarification on this post, please mention in the comment section.
Comments