top of page

Magento 2 script tag and available options in layout xml

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

  1. 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)

  2. If async is not present and defer is present: The script is executed when the page has finished parsing

  3. 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.

Recent Posts

See All

Comments


Follow Me

  • LinkedIn
  • Twitter
  • Facebook
  • YouTube
  • Instagram

©2021 by Bilal Usean. Proudly created with Wix.com

bottom of page