[JavaScript] Cache Busting一定時間更新れるエリ作成する方法

2 min read
hiroweb developer

Cache Busting とは

下記のように URL に意味のないクエリを付与して、キャッシュコントロール行うことを「Cache Busting」と呼ぶ。

<link href="style.css?20171221" rel="stylesheet" />
<script src="script.js?20171221"></script>

方法

HTML 上でクエリを付与するのであれば、バックエンドの処理で付与したり、アセットパイプライン、タスクランナーなどで付与すれば良い。
ただ、JS 内の処理だと何らかの方法でクエリを付与する必要がある。

ライブラリ依存のケース

Moment.js を使うケース

ライブラリを使用せずピュアな JS だけで実装は可能だが、日付を操作するのは大変なので Moment.js を利用したケース。

function createCacheBusting(thresholdMinutes = 15) {
  const start = moment();
  const remainder = thresholdMinutes - (start.minute() % thresholdMinutes);

  return moment(start).add("minutes", remainder).format("YYYYMMDDHHmm");
}

コード

特定のライブラリに依存しない実装は以下。

function createCacheBusting(thresholdMinutes = 15) {
  const date = new Date();
  const minutes = date.getMinutes();
  const remainder = thresholdMinutes - (minutes % thresholdMinutes);

  return new Date(date.setMinutes(remainder + minutes))
    .toISOString()
    .replace(/[^0-9]/g, "")
    .slice(0, -5);
}
const cacheQuery = createCacheBusting();

fetch(`${url}?${cacheQuery}`).then(function (data) {
  // process data
});
  • 引数なしだと「201712211715」みたいな感じで 15 分毎にクエリが更新される
  • 引数のthresholdMinutes3060を渡すことで 30 分毎・60 分毎にクエリが更新されるようになる