[jQuery] カルーセルライブラリ slick.js の lazyLoad を理解する

jQuery のカルーセルライブラリ slick.js をそのまま使うと slick.js file の読み込みと .slick() method の実行が完了するまで、カルーセルのレイアウトにならず ul, li タグで囲んでいる画像が全て表示されてしまうという問題に直面しました。

jQuery | ジェイクエリー

これを解決するには 1 枚目の画像だけ src で画像 URL を指定します。

<img src="http://example.com/image1.png">

2 枚目以降は data-lazy attribute に image url を指定します。

<img data-lazy="http://example.com/image2.png">

そして .slick() method に lazyLoad オプションを設定してあげれば OK です。

$('#js-banner-area').slick({
  lazyLoad: 'progressive'
});

Lazy Loading のサンプルは slick – the last carousel you'll ever need に載っています。

ちなみに lazyLoad オプションは ondemand と progressive の 2 つの設定があります。挙動の違いは Stack Overflow に詳しく説明されている投稿があったので引用しておきます。

ondemand: Loads the visible image as soon as the page is displayed and the other ones only when they’re displayed. (“[…] loads slides on demand. When a slide becomes visible (or on the before slide callback) the load is fired.”) Should be used if the other images of the carousel are displayed very rarely.

progressive: Loads the visible image as soon as the page is displayed and the other ones after everything else is loaded in the background (“loads the visible slides on init, and then progressively loads the rest of the slides on window.load().”). Should be used if the other images will be used most (or all) of the times the page is displayed.

デフォルトは画像が表示されるタイミングで load 処理が動く ondemand ですが、個人的には background で画像を load しておいてくれる progressive オプションを使うのが好みです。

lazyLoad オプションに設定値はカルーセルで 2 枚目以降の画像が表示される頻度で ondemand を使うか progressive を使うかを決めるとよさそうですね。

参考情報