0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Cache Busting とは?

Last updated at Posted at 2025-04-14

Cache Busting とは?

ブラウザは、Webページの読み込みを高速化するために、CSSやJavaScript、画像などの静的リソースをキャッシュします。それにより、ファイルを更新してもキャッシュが残っていると古いファイルが読み込まれてしまうことがあります。

これを解決するために、ブラウザのキャッシュを回避し、最新のリソースを確実に読み込ませるための手法がCache Bustingです。

実装方法

リソースのURLにクエリパラメータを付与します。

基本

CSSやJavaScriptファイルの読み込み時にクエリパラメータを追加するだけでOK

<!-- バージョン番号を付与する例 -->
<link rel="stylesheet" href="style.css?v1.2.3">
<script src="app.js?v1.2.3"></script>
<!-- タイムスタンプを付与する例 -->
<link rel="stylesheet" href="style.css?v1700000000">
<script src="app.js?v1700000000"></script>

PHP の場合(サーバーサイドで自動化)

filemtime() を使うことで、ファイルの更新時刻をクエリパラメータに適用できます。

<link rel="stylesheet" href="style.css?v<?php echo filemtime('style.css'); ?>">
<script src="app.js?v<?php echo filemtime('app.js'); ?>"></script>

Laravel Blade の場合

mix() を使うことで、バージョン管理が可能です。

<link rel="stylesheet" href="{{ mix('css/style.css') }}">
<script src="{{ mix('js/app.js') }}"></script>

または、asset() を使い filemtime() を適用する方法もあります。

<link rel="stylesheet" href="{{ asset('css/style.css') }}?v{{ filemtime(public_path('css/style.css')) }}">

JavaScript で動的に設定

JavaScript を使って Date.now() をクエリパラメータに追加する方法もあります。

const timestamp = Date.now();
document.write(`<script src="app.js?v${timestamp}"><\/script>`);
0
0
3

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?