LoginSignup
0
0

More than 3 years have passed since last update.

MoOx/pjaxでブラウザーキャッシュ対策のクエリー文字列が付かないようにする方法

Posted at

内容

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;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0