LoginSignup
39
38

More than 5 years have passed since last update.

jQuery.lazyloadを使ってAutopagerを実装する

Last updated at Posted at 2012-12-11

tuupola/jquery_lazyload は本来 img タグを遅延読み込みするための jQuery プラグインだがその実体は jQuery オブジェクトが画面に出現したら appear イベントを発行するものなので、appear イベントにコールバックをバインドすれば「続きを読み込む」機能を簡単に実装できる。

例えば /timeline に timestamp でタイムスタンプを指定すればそこを起点として何件かとって来てくれるAPIが実装されており、タイムラインの各div要素の data-timestamp 属性がそのポストのタイムスタンプを表しているとすれば、これらを使って次のようにAutopagerを実装できる。

var loading = false;
$('#more')  // "もっと見る" ボタン
  .lazyload({ threshold: 200 })  // 200px 余裕をもって appear イベントを発行
  .on('appear', function () {
    if (loading) return;  // 非同期通信を抑制する
    loading = true;
    $.getJSON('/timeline', { timestamp: $('.timeline-item:last-child').data('timestamp') })
      .done(function (data) {
        // data を挿入する
        loading = false;
      })
      .fail(function () {
        // ユーザにエラー通知
        // loading は true のままにすれば以降非同期通信は発生しない
      });
  })
39
38
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
39
38