Magento – Defer JS / CSS Magento 2 via layout files

cssheaderjavascriptlayoutmagento2

After reading a lot of devdocs, I can see there is a case for deferring in CSS and JS in the manual

https://devdocs.magento.com/guides/v2.3/frontend-dev-guide/layouts/layout-types.html#layout-types-conf

However, I can not seem to get this method to work. I'm either placing the files in the wrong location, naming them incorrectly, or just not using the correct syntax as none is provided in the docs.

I've tried placing different methods inside app/design/frontend/theme/name/Magento_Theme/layout/default_head_blocks.xml but I've had no luck, other than removing some of the CSS, as described in

https://devdocs.magento.com/guides/v2.3/frontend-dev-guide/layouts/xml-instructions.html

I don't seem to be able to remove any JS via the default_head_blocks.xml nor implement the defer to any CSS or JS. And to be honest, the directions in the docs are confusing and many of the examples, don't include the features. Or the directory structure doesn't exist. My Magento theme files are all inside /vendor/magento/ and not in /app/design/ – I am using a cloned copy of Luma where I changed the registration and other files to be able to use it as a renamed theme, but the XML layout instructions are not very well done.

If anyone knows what syntax to use to defer CSS or JS in the header, it would be greatly appreciated as ever method I've tried seems to have no effect.

Best Answer

You can defer parse the JS or CSS using the attribute defer

<script src="name.js" defer="defer"></script>
<css src="name.css" defer="defer"/>

Hope it helps you.

Related Topic