This is basically the opposite of fetch(), how do you make a non-cached request?.
Let's say we have client-side:
<div onclick="fetch('/data.php').then(r => r.text()).then(s => console.log(s));">Click me</div>
and server-side in PHP:
<?php echo "hello"; /* in reality, this can be much more data
and/or updated later with other content */ ?>
When clicking multiple times on Click me
, the request is done multiple times over the network with request response code "200".
Thus, no caching has been done by the browser / by PHP:
How to prevent this data to be transferred multiple times if it is in fact not needed here?
Potential solution: Since /data.php
can be updated on the server, the server could serve the data requests with a datetime metadata timestamp
, that I could store in a client-side JS variable timestamp
. Then before doing the next fetch
request for /data.php
, I could do a preliminary request
fetch('/get_last_modification_date.php').(r => r.json()).then(data => {
if (data['timestamp'] != timestamp)
fetch('/data.php')... // if and only if new data is here
});
Thus, we only do a fetch('/data.php')...
if the timestamp of this data is more recent than the one we already had.
This would work, but it seems we are manually doing something that could be done by the browser+PHP cache mechanism.
How to ask PHP and the browser to do all this caching for us?