I have solved my problem using ajax post request on phtml file
So I have created two phtml files and in my first phtml file which show the output data on page reload I have called the ajax post request to my custom controller
<div id="customdata"></div>
<?php
$ajaxurl = $block->getAjaxUrl();
?>
<script type="text/x-magento-init">
{
"*": {
"Mymodule_Custom/js/custom": {
"AjaxUrl": "<?php echo $ajaxurl; ?>",
"CurrentProduct": "<?php echo $currentProductId; ?>",
}
}
}
</script>
and then in controller called another phtml file and load content from that phtml file using below type of code.
$result = $this->_resultJsonFactory->create();
$resultPage = $this->_resultPageFactory->create();
$currentProductId = $this->getRequest()->getParam('currentproduct');
$data = array('currentproductid'=>$currentProductId);
$block = $resultPage->getLayout()
->createBlock('Mymodule\Custom\Block\Index\View')
->setTemplate('Mymodule_Custom::customview.phtml')
->setData('data',$data)
->toHtml();
$result->setData(['output' => $block]);
return $result;
and in this customview.phtml I have loaded my dynamic content and then set to first phtml file using ajax response and it work fine with cache
<?php
$productData = $block->getData();
$productId = $productData['data']['currentproductid'];
$products = $block->getProducts($productId);
?>
<div>
<div>YOUR HTML</div>
</div>