Skip to content

Commit

Permalink
Ignore initial server requests if cached and stale
Browse files Browse the repository at this point in the history
Staleness is determined by seeing if the Last-Modified value is older than the current request by the length of the refresh rate plus a 10 second grace period.

This check will only run for the initial request to /live_cache_check/1/, as it's assumed that the other urls, which are time based, won't need such aggressive cache busting.

If the cache is stale, this will set the timeStamp variable to the current time and immediately rerun check().
  • Loading branch information
John P. Bloch committed May 7, 2014
1 parent 548b005 commit de90a61
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion live-cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
};

this.check = function () {
var self = this;
if (undefined === runCache || null === runCache) {
$.each(self.auto_updates, function () {
var selector = "" + this;
Expand All @@ -58,13 +59,24 @@
url : ajaxurl + '/live_cache_check/' + timeStamp + '/',
success : function (data, s, resp) {
var date = resp.getResponseHeader('Date'),
serverTime = Math.round((new Date(date)).getTime() / 1000);
serverTime = Math.round((new Date(date)).getTime() / 1000),
lastModified = resp.getResponseHeader('Last-Modified'),
lastModifiedTime;

data.refresh_rate = getRefreshRate(data.refresh_rate || 0);

// look only at the tens place of the second counter to refresh cache every ten seconds.
timeStamp = formatTimestampEndpoint(int_to_timestamp(serverTime + data.refresh_rate));

if (lastModified && /\/live_cache_check\/1\/?$/.test(this.url)) {
lastModifiedTime = Math.round((new Date(lastModified)).getTime() / 1000);
if (lastModifiedTime + data.refresh_rate + 10 < serverTime) {
timeStamp = formatTimestampEndpoint(int_to_timestamp(serverTime));
self.check();
return;
}
}

$.each(data, function (key, value) {
if (undefined !== callbacks[key] && (undefined === values[key] || values[key] !== value)) {
callbacks[key].fire(key, value); //pass key and value so that we can use the same callback for multiple keys
Expand Down

0 comments on commit de90a61

Please sign in to comment.