I need to add custom css in head dynamically, where css url is dynamic.

I can add using below code but page will get cache, I need to add css dynamically each page re-fresh, css url will be also changed.

        <referenceBlock name="head.additional">
            <block class="NAMESPACE\CUSTOMMODULE\Block\CustomCss" name="custom_css" template="customCss.phtml" before="-"/>

Its some thing like CDN. Each time when css changed my custom css URL also change.


By default all the blocks are assumed to be cacheable, but you can prevent chaching of any specific block by setting cacheable attribute as false in the XML file.

Example -

In Magento_Customer::view/frontend/layout/customer_account_index.xml file, you can find following piece of code

<referenceContainer name="content">


<block class="Magento\Customer\Block\Account\Dashboard\Info" name="customer_account_dashboard_info" as="info" template="account/dashboard/info.phtml" cacheable="false"/>

<block class="Magento\Customer\Block\Account\Dashboard\Address" name="customer_account_dashboard_address" as="address" template="account/dashboard/address.phtml" cacheable="false"/>


You can see that the above block are set as non-cacheable by using cacheable="false" attribute.

Similarly you can also do the same with your code and then in your phtml file (customCss.phtml file), you can load the CSS file normally like following -

<link rel="stylesheet" type="text/css" media="all" href="<?php echo $_helper->yourCssFile()?>">

And you can get the dynamic url of your CSS file using yourCssFile() function. As the page will not be chached so every time, new CSS file will get loaded. But there is a price of doing this. cacheable="false" will disable the cache for whole block and will make the page slower to load.

For more information you can visit the following URL -: http://devdocs.magento.com/guides/v2.0/config-guide/cache/cache-priv-priv.html

  • cacheable="false" not working under <referenceBlock name="head.additional"> you can try it – Pradeep Kumar Mar 7 '17 at 5:23

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.