LoginSignup
28
28

More than 5 years have passed since last update.

jQuery Lazyloadプラグインで遅延読み込み

Posted at

画像の遅延読み込みができるjQueryプラグインを導入してみた。

jquery_lazyloadを使用。有名らしい。

使い方

sample.html.erb
<%= javascript_include_tag "jquery" %>
<%= javascript_include_tag "jquery_lazyload" %>

<script>
$(function(){
  $("img.lazy").lazyload({ effect: 'fadeIn', threshold: '200' });
});
</script>

<img src="loading.gif" class="lazy" data-original="hoge.png" width="200" height="200">

jQueryとlazyloadプラグインを読み込み上記のようなスクリプトを書けば、lazyクラスを持つ画像が遅延表示される。

注意点としては、img要素のsrc属性にはダミー画像を書いておき、本物の画像ファイルをdata-original要素に書いておくこと。

細かいオプションに関しては、公式ページとかで確認。

railsで利用するにあたり、適当なメソッドを作った。

app/helpers/application_helper.rb
def lazy_image_tag(source, options={})
  options['data-original'] = source
  if options[:class].blank?
    options[:class] = "lazy"
  else
    options[:class] = "lazy #{options[:class]}"
  end

  image_tag('transparent.gif', options)
end

jsのスクリプトを書いておき、上記のメソッドを使えば、画像が遅延読込されるようになる。

参考

画像を遅延ロードする定番jQueryプラグイン「Lazy Load」

28
28
0

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
28
28