内容
MoOx/pjaxでは、cacheBust
オプションがtrue
(デフォルト)になっていると、ページ遷移時にブラウザーキャッシュ対策のクエリー文字列が追加されます。
このクエリー文字列だけを自動で削除するコードです。
コード
JavaScript
const pjaxInstance = new Pjax({
// 省略
});
pjaxInstance.latestChance = function(href) {
Pjax.prototype.latestChance.call(
this,
this.options.cacheBust ? removeTimestampQuery(href) : href,
);
};
pjaxInstance.afterAllSwitches = function() {
if (this.options.cacheBust) {
this.state.href = removeTimestampQuery(this.state.href);
}
Pjax.prototype.afterAllSwitches.call(this);
};
function removeTimestampQuery(href) {
const anchor = document.createElement('a');
let searchString;
let parameters;
anchor.setAttribute('href', href);
searchString = anchor.search;
if (searchString.length > 0) {
parameters = searchString.slice(1).split('&');
parameters = parameters.filter(function(element) {
return element.indexOf('t=') !== 0;
});
anchor.search = parameters.length > 0 ? '?' + parameters.join('&') : '';
href = anchor.href.replace(/\?$/, ''); // for IE
}
return href;
}