Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

内容

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;
}
wd-flat
フロントエンドの価値を高めるコーディング専門プロダクション
http://wd-flat.com
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away