0

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.

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"/>
0

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.