jQueryでスクロールのイベントを確認してみる

jQueryでタップ系のイベントを確認してみる
の続き

スマホでは、頻繁に発生するscrollイベントで何か処理を行うと
重くなるみたいなので、
jQueryでスクロールのイベントを確認し、プラグインを試してみる。

確認用のHTML

<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,user-scalable=no">
  <script src="https://code.jquery.com/jquery-2.2.0.js"></script>
  <style>
  #dummy {
    width: 1px;
    height: 5000px;
  }
  #log {
    position: fixed;
    top: 0;
    right: 0;
    padding: 10px;
    background-color: #eee;
  }
  </style>
</head>
<body>
  jQueryのイベント確認<br>
  (スクロール編)<br>

  <div id="dummy"></div>
  <div id="log"></div>

  <script>
    $(window).on("scroll", function(event) {
      $("#log").prepend("<div>" + event.type + " " + $(this).scrollTop() + "</div>");
    });
  </script>
</body>
</html>

スクロールイベントが大量に発生しているのが確認できる。
確認ページ


jQuery throttleでscrollの頻度を抑えてみる

下記のサイトから、jquery.ba-throttle-debounce.min.jsをダウンロードする。

Ben Alman » jQuery throttle / debounce: Sometimes, less is more!
http://benalman.com/projects/jquery-throttle-debounce-plugin/

ダウンロードしたファイルをheadに指定し、

  <script src="js/jquery.ba-throttle-debounce.min.js"></script>

$.throttle(ミリ秒, …) で囲む。

    $(window).on("scroll", $.throttle(1000, function(event) {
      $("#log").prepend("<div>" + event.type + " " + $(this).scrollTop() + "</div>");
    }));

画像からは分からないが、scrollイベントが1秒毎に発生しているのが確認できる。
確認ページ


jQuery mobileでscrollのイベントを追加してみる

前回の記事でダウンロードしたjsファイルを追加する。

  <script src="js/jquery.mobile.custom.js"></script>

scriptを下記のように修正する。

    var events = [
      "scroll",
      "scrollstart",
      "scrollstop"
    ];
    for (var i in events) {
      $(window).on(events[i], function(event) {
        $("#log").prepend("<div>" + event.type + " " + $(this).scrollTop() + "</div>");
      });
    }

scrollstartとscrollendのイベントが発生しているのが確認できる。
確認ページ


jquery-scrollstop

下記のjquery-scrollstopというプラグインでも

ssorallen/jquery-scrollstop: A jQuery plugin that fires events when scrolling stops and starts.
https://github.com/ssorallen/jquery-scrollstop

scrollstop/scrollstartのイベントを追加できる。
確認ページ