レスポンシブ対応で画像がPC用とSP用で違うものを使いたい場合
PC用とSP用の画像を2枚用意していてcssもレスポンシブで出し入れする場合、結局画像をdisplay noneで非表示にしているだけで読み込んでいるのでサイトの読み込み速度が遅くなります。
そんなときにはjQueryで画面サイズによって画像を出し分けしましょう。
PC用とSP用の画像を用意
例えばtest.jpgという画像があった場合
PC用
PC用の画像の名前はtest_pc.jpg
SP用
SP用の画像の名前はtest_sp.jpg
htmlファイルに記述
<img src="test_pc.jpg" alt="" class="image-switch">
class名をimage-switchとしてください。
jsファイルに記述
$(function() {
var $elem = $('.image-switch');
var sp = '_sp.';
var pc = '_pc.';
var replaceWidth = 768;
function imageSwitch() {
var windowWidth = parseInt($(window).width());
$elem.each(function() {
var $this = $(this);
if(windowWidth >= replaceWidth) {
$this.attr('src', $this.attr('src').replace(sp, pc));
} else {
$this.attr('src', $this.attr('src').replace(pc, sp));
}
});
}
imageSwitch();
var resizeTimer;
$(window).on('resize', function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
imageSwitch();
}, 200);
});
});
これだけでレスポンシブ対応の画像の出し分けが可能になります!
参考にどうぞ。