Magento 2: How Can Add Js/Css Through Layout Update XML File

Magento 2 introduced <head /> and <body /> nodes which we can use in our layout update xml file in order to change it’s contents. However this raises lot of confusions. Here I would like to discuss about a loosely coupled feature (or bug ?) which we can see if tries to add js/css via layout update xml file. Following code will add a js into our page.
File : app\code\Namespace\Module\view\frontend\layout\something_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <link src="Namespace_Module::test.js" />
    </head>
</page>

If you are in developer mode and after you cache is cleaned , then after loading you specific page you will see your test.js file in page source. Now the same result we can achieve using following XML update.

Update 1 : Using <script /> Node.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="Namespace_Module::test.js" />
    </head>
</page>

Update 2 : Using <css /> Node.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="Namespace_Module::test.js" />
    </head>
</page>

Both these changes will assert test.js into your page source. Wait .. did <css /> node worked to add a js file ? The answer is Yes. You can interchangably use any of <link />, <script /> or <css /> in order to add a js or css file.

ie, you can use <script /> node in order to add a CSS file and you can use <css /> node in order to add a JS file, which may arise confusion among developers.

What is your opinion regarding this ? Please let me know through comment section.

Rajeev K Tomy

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top