LoginSignup
0
0

More than 3 years have passed since last update.

LodashのthrottleでonScroll処理

Posted at

lodashを読み込む

<script src="lodash.js"></script>

npmで読み込む場合

$ npm i --save lodash

スクロール時、1秒毎にhoge実行

$(function() {
  $(window).on('scroll', _.throttle( hoge, 1000 ));
});

hoge = ヘッダーを表示する。など

function hoge(){
  var scroll = $(window).scrollTop();
  if(scroll > 10){
    $("header").removeClass("hide");
  }else{
    $("header").addClass("hide");
  }
}

なんでlodash.jsが必要?

「スクロールしている」という状態が1秒に何十回もあるので、
$("header").removeClass("hide");
を何十回も実行しちゃって重たくなってしまう。
lodashはそこを間引いてくれる。

利用シーン

jQueryなどを書く時に
$(window).on("scroll"...あっlodash入れなきゃ、という感じで
使う事が多いです、という話です。

参考にした記事

https://lodash.com/
https://lodash.com/docs/4.17.15#throttle

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