Skip to content

Instantly share code, notes, and snippets.

@appelgran
Created April 16, 2020 19:29
Show Gist options
  • Save appelgran/68be1091c1584f6ce8ed8f0e44e8755a to your computer and use it in GitHub Desktop.
Save appelgran/68be1091c1584f6ce8ed8f0e44e8755a to your computer and use it in GitHub Desktop.
JS/PHP - Send cache and renew cache without waiting for the renewal
<?php
//
// Outputcache
$cache_time_in_seconds = 600;
$cache_file_name = 'news-external.b.php.outputcache';
$echo_output_after_save = true;
if (file_exists($cache_file_name)) {
// Cache exists
if (time() - filemtime($cache_file_name) < $cache_time_in_seconds) {
// Cache is fresh
// print from cache and exit
echo file_get_contents($cache_file_name);
exit;
}
else {
// Cache needs renewal
// print from cache, flush it and let renewal be made (but not echoed)
echo file_get_contents($cache_file_name);
flush();
$echo_output_after_save = false;
}
}
//
// Load heavy content
$dummy_content = 'such heavy';
//
// Outputcache och echo
$output = $dummy_content . '<!-- end-of-content=true -->';
// Save outputcache
file_put_contents($cache_file_name, $output);
// Echo maybe
if ($echo_output_after_save) {
echo $output;
}
?>
<section>
<h2>External news</h2>
<p class="js-news-external-loading">Loading...</p>
<div class="js-news-external-entries"></div>
</section>
<script>
(function() {
// Load external news entries
var ajax = new XMLHttpRequest();
var responseWritten = false;
ajax.onreadystatechange = function() {
// Wait for http status 200 OK and...
// ...readyState 4 DONE or...
// ...readyState 3 LOADING and content indicating all content has been received
if (!responseWritten && ajax.status === 200 && (ajax.readyState === 4 || (ajax.readyState === 3 && ajax.responseText.indexOf("<!-- end-of-content=true -->") > -1))) {
// Remove loading text
document.querySelector(".js-news-external-loading").classList.add("hidden");
// Print the news entries
document.querySelector(".js-news-external-entries").innerHTML = ajax.responseText;
responseWritten = true;
}
};
ajax.open("GET", "/news-external.b.php", true);
ajax.send();
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment