5
3

More than 3 years have passed since last update.

モーダルウィンドウを開いたときだけ画像をロードする

Last updated at Posted at 2019-09-27

画像を遅延ロードしてるのにPSIのスコアがなぜか低い、と思ったらモーダルウィンドウ内の画像が遅延ロードされていなかったのでメモ
ただしこの方法だとモーダルウィンドウを開いたときにモーダル内の画像が全て読み込まれるので注意

モーダルウィンドウを開いたときだけモーダル内の画像をロードする

ざっくり書くとimgタグのsrcに読み込み前の画像、data-srcに読み込み後の画像を配置して、
モーダルウィンドウが開いたときにjQueryでdata-srcをsrcに代入しています。

モーダルウィンドウはBootstrap4で実装しています。

modalwindow
<!-- モーダルの設定 -->
<div class="modal fade myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog modal-xl" role="document">
    <div class="modal-content">
      <div class="modal-body text-center">
        <!-- srcに読み込み前の画像、data-srcに読み込み後の画像 -->
        <img class="lazy_load" src="noimage.jpg" data-src="something.jpg">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

jQueryは以下のようになります

modalwindowlazyload
$('.myModal').on("show.bs.modal", function () {
  $('.lazy_load').each(function(){
      var img = $(this);
      img.attr('src', img.data('src'));
  });
});

おわり

5
3
1

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
5
3