I have added java-script in the footer like below and I am passing the customer email dynamically, but the same email id is displaying for all the customers because the page is caching.
Please help me to fix this cache issue.
First of all, avoiding using Object Manager directly in our template. This is not good for best practice. Should create a new block and try to apply the solutions below:
after.body.start
or before_body_end
[Seem that these blocks are cached]
These blocks are not cached. So, we can add your custom block to these containers. For example:
Company/Module/view/frontend/layout/default.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="before.body.end">
<block class='Company\Module\Block\Module' name="js.tracking" as="js.tracking" template="Company_Module::tracking.phtml"/>
</referenceContainer>
<!--<referenceContainer name="after.body.start">-->
<!--<block class='Company\Module\Block\Module' name="js.tracking" as="js.tracking" template="Company_Module::tracking.phtml"/>-->
<!--</referenceContainer>-->
</body>
</page>
Add tracking js to your custom template: Company/Module/view/frontend/templates/tracking.phtml
Should take a look at Google Analytics module: vendor/magento/module-google-analytics
.
Read more here: How do disable caching of custom block on product view page?. However, currently, this way should not try because make the pages contain this block uncacheable.
I like this way, we should try with Ajax.
--Suggests other solutions:
Magento 2 stores cart info on local storage, we can add more customer info to cart info. And then, use it in our custom script.
Go to vendor/magento/module-checkout/view/frontend/templates/onepage.phtml
, we can see that Magento uses some global variables to store checkout info(including customer data).
cacheable="false"
prevents the whole page from being cached, not enough people know about this.
Commented
Mar 23, 2017 at 16:12