1

I want to add the async attribute to a script tag in the <head> block. I've successfully added the script tag to the default_head_blocks.xml file in Magento_Theme as per the example in the Devdocs, but can't work out how to add an additional attribute to the tag with Magento 2.

I've tried:

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" src_type="url" async="async"/>

but this doesn't work.

asked Aug 18, 2017 at 12:40

2 Answers 2

1

I wasn't able to do this using Layout XML as I would have in Magento 1. Instead I used the approach in https://magento.stackexchange.com/a/92908/55634

In default.xml I added a new template to the head.additional block:

<body>
 <referenceBlock name="head.additional">
 <block class="Magento\Framework\View\Element\Template" name="custom-head-assets" template="head/custom-head.phtml" />
 </referenceBlock>
</body>

Note it's important that this block is added within <body> - although the template will actually be output in the <head>.

Then in the template I can add HTML for <script> and <link> tags with whatever attributes I want, e.g.

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" async></script>
answered Aug 24, 2017 at 9:30
0

You should create that JS file in your module and use below code.

<script async="async" src="Vendor_ModuleName::js/bootstrap.min.js"/>

if you want to use in Theme

<script async="async" src="js/bootstrap.min.js"/>

For defer, You can follow the below code :

<script defer="defer" src="js/bootstrap.min.js"/>
Rohan Hapani
17.6k9 gold badges57 silver badges99 bronze badges
answered Aug 18, 2017 at 15:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.