こちらの記事の続きです。
ここで紹介するのは、あくまでアイディアの一例です。
なので、開発ツール・言語・フレームワークなどご自身の事情にあわせて適宜調整して下さい。
少しでもキャッシュで困っている方へのヒントになれば幸いです。
新たに見つけたり思いついたら、順次追記していきます。
HTML・CSS (手動)
まずは基本系として、プレーンなHTMLでの方法です。HTMLのキャッシュ更新を強制します。
例として、style.css の内容を変更したら手作業でクエリを書き換えてみます。
以下でご紹介する方法の出力例がこんな感じになりますね。
<link rel="stylesheet" href="style.css?ver=12345">
CSSの中で使う場合はこんな感じ。
.img {
background-image: url(example.jpg?ver=12345);
}
WordPress・PHP
スタイルシートを読み込む際に、PHPの関数を使って現在の時間を読み込んでみます。
<link rel='stylesheet' href='<?php bloginfo('stylesheet_url');?>?ver=<?php echo date("His") ?>'/>
functions.phpから、テーマのバージョン番号を読み込むならこんな感じでしょうか。
function theme_enqueue_styles() {
wp_enqueue_style(
'mytheme-style',
get_stylesheet_uri(),
array(),
wp_get_theme()->get( 'Version' )
);
functions.phpから、子テーマに更新時刻を反映させる場合はこんな感じでしょうか。
function theme_enqueue_styles() {
wp_enqueue_style(
'parent-style',
get_template_directory_uri() . '/style.css'
);
wp_enqueue_style(
'child-style',
get_stylesheet_directory_uri() . '/style.css',
array('parent-style'),
date("ymdHis",filemtime( get_stylesheet_directory().'/style.css'))
);
}
add_action('wp_enqueue_scripts', 'theme_enqueue_styles');
試しにカスタムフィールドでもやってみます。
<link rel='stylesheet' href='<?php bloginfo('stylesheet_url');?>?ver=<?php the_field('カスタムフィールド名'); ?>'/>
PHP
date関数で現在の時間を読み込んでみます。
WordPressの1例目とほぼ同じです。
<link rel='stylesheet' href='style.css?ver=<?php echo date("His") ?>'/>
filemtime関数でファイルの更新時刻を読み込んでみます。
<link rel="stylesheet" href="style.css?ver=<?php echo filemtime( 'style.css' ); ?>">
JavaScript
色々と制約がある場合にはJavaScriptでも良いのかも。冗長に感じるのであまり好きでは無いですが…。
const now = new Date()
const y = "" + now.getFullYear();
const m = ("00" + (now.getMonth()+1)).slice(-2);
const d = ("00" + now.getDate()).slice(-2);
document.write(`'<link rel="stylesheet" href="style.css?${y+m+d}">`);
【参考】
javascriptでcache-bustingを自動化する方法
https://ja.stackoverflow.com/questions/43918/javascriptでcache-bustingを自動化する方法
EC CUBE4 (twig)
管理画面で「キャッシュ削除」も忘れずに。
<link rel="stylesheet" href="style.css?{{ "now"|date("His") }}">
EC-CUBEのテンプレートタグについての記事を書きました。こちらも参照下さい。
SCSS(CSS内のパスにクエリを追加)
CSS内のリンクにクエリを追加してみても良いですね。
【参考】
Sass unique-id
https://sass-lang.com/documentation/modules/string#unique-id
1 件のコメントが “Cache Busting(キャッシュバスティング)の具体例” にあります。