0

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.

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

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

0

2 Answers 2

0

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

</referenceContainer>

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

1
  • cacheable="false" not working under <referenceBlock name="head.additional"> you can try it Mar 7, 2017 at 5:23
0

If you want to add a custom css you not need to create a custom block for it. Magento by default provide this facility to add CSS in header section.

Login to Admin and follow the steps:

Content -> Design -> Configuration -> Select current enabled theme for your store -> Click on "HTML Head"->  Write your css and scripts in "Scripts and Style Sheets"

Your Answer

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

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