Utilizing varnish+esi, I am able to retrieve external json content from a RESTFul API. This approach allows for efficient request management and data refreshing without burdening the webserver with each individual request.
For example:
<head>
....
<script>
var data = <esi:include src='apiurl/data'>;
</script>
...
Upon including the ESI, Varnish will return:
var data = {attr:1, attr2:'martin'};
While this method works well, it may encounter parsing errors if the API responds with an error message.
var data = <html><head><script>...api js here...</script></head><body><h1 ... api html ....
To resolve this issue, I implemented a hidden div to manage and capture any potential errors:
...
<b id=esi-data style=display:none;><esi:include src='apiurl/data'></b>
<script>
try{
var data = $.parseJSON($('#esi-data').html());
}catch{ alert('manage the error here');}
....
I also experimented with using a script type text/esi, but encountered issues where the browser would render the HTML within the script tag (strange behavior), as seen here:
<script id=esi-data type='text/esi'><esi:include src='apiurl/data'></script>
Question:
Is there a way to encapsulate the esi:include tag to prevent the browser from parsing it?