はじめに
Webサイト開発において、画像パスを動的に変更する必要が生じることがあります。今回は、テスト環境と本番環境で画像パスが異なる場合に、JavaScriptを使用して動的に画像パスを変更する方法を紹介します。
なぜ画像パスの動的変更が必要なのか?
画像パスの動的変更が必要になるケースはいくつかあります:
- 開発環境と本番環境の違い
- CMS移行
- ドメイン変更
- CDN導入
- セキュリティ強化(HTTPSへの移行)
- サーバー構成の変更
- 国際化対応
- A/Bテスト
- パフォーマンス最適化
- コンテンツデリバリーの最適化
今回は、テスト環境と本番環境で画像パスが異なる場合を例に、解決方法を見ていきます。
実装例
以下は、テスト環境でのみ画像パスを変更するJavaScriptのコードです:
document.addEventListener('DOMContentLoaded', function() {
// テスト環境かどうかをチェック
if (window.location.href.includes('example-test.com')) {
const oldPath = '/content/images/main/2024/';
const newPath = '/test-images/2024/';
// img と source タグの属性を変更
const mediaElements = document.querySelectorAll('img, source');
mediaElements.forEach(el => {
const attributesToChange = ['src', 'srcset', 'data-src', 'data-src0', 'data-src744'];
attributesToChange.forEach(attr => {
if (el.hasAttribute(attr) && el.getAttribute(attr).includes(oldPath)) {
el.setAttribute(attr, el.getAttribute(attr).replace(new RegExp(oldPath, 'g'), newPath));
}
});
});
// style属性内のbackground-imageを変更
const elementsWithBgImage = document.querySelectorAll('[style*="background-image"]');
elementsWithBgImage.forEach(el => {
const style = el.getAttribute('style');
if (style.includes(oldPath)) {
const newStyle = style.replace(new RegExp(oldPath, 'g'), newPath);
el.setAttribute('style', newStyle);
}
});
// インラインスタイルシート内のurl()を変更
const styleSheets = document.styleSheets;
for (let i = 0; i < styleSheets.length; i++) {
const rules = styleSheets[i].cssRules || styleSheets[i].rules;
for (let j = 0; j < rules.length; j++) {
if (rules[j].style && rules[j].style.backgroundImage) {
rules[j].style.backgroundImage = rules[j].style.backgroundImage.replace(new RegExp(oldPath, 'g'), newPath);
}
}
}
}
});コードの解説
DOMContentLoadedイベントリスナーを使用して、DOMの読み込みが完了した後にスクリプトを実行します。window.location.href.includes('example-test.com')で、現在のURLにテスト環境のドメインが含まれているかをチェックします。imgとsourceタグのsrc,srcset,data-src,data-src0,data-src744属性を変更します。style属性内のbackground-imageを変更します。- インラインスタイルシート内の
url()関数で指定された画像パスも変更します。
注意点
- このスクリプトは、ページ読み込み後に動的に追加された要素には影響しません。
- JavaScriptが無効化されている環境では機能しません。
- 大量の要素や複雑なスタイルシートがある場合、パフォーマンスに影響する可能性があります。
まとめ
このテクニックを使用することで、テスト環境と本番環境で異なる画像パスを簡単に管理できます。ただし、可能な限りサーバーサイドでの解決や、ビルドプロセスでの静的な置換を検討することをおすすめします。状況に応じて最適な方法を選択してください。

