[Javascript] 元素顯示狀態監測: IntersectionObserver

IntersectionObserver API
https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

IntersectionObserver polyfill
https://github.com/w3c/IntersectionObserver/tree/master/polyfill

IntersectionObserver 正在來到我們的視野
http://www.qingpingshan.com/pc/llq/146494.html

IntersectionObserver API 使用教程
http://www.ruanyifeng.com/blog/2016/11/intersectionobserver_api.html

各瀏覽器支援度
https://caniuse.com/#feat=intersectionobserver

在移動端,有個很重要的概念,叫做懶載入,適用于一些圖片資源特別多,ajax 資料特別多的頁面中,經常會有動態載入資料的場景中,這個時候,我們通常是使用監聽 scroll 或者使用 setInterval 來判斷,元素是否進入視圖,其中 scroll 由於其特別大的計算量,會有性能問題,而 setInterval 由於其有間歇期,也會出現體驗問題。

IntersectionObserver 就是為此而生的,它讓檢測一個元素是否可見更加高效,而且已經在 Chrome 51 中實現。 IntersectionObserver 能讓你知道一個被觀測的元素什麼時候進入或離開流覽器的視口,顯示或隱藏,而不需要頻繁的計算來做這個判斷。

另外 IntersectionObserver API 是非同步的,不隨著目標元素的滾動同步觸發,且規格寫明,IntersectionObserver 的實現採用 requestIdleCallback,即只有執行緒空閒下來,才會執行觀察器。由於流覽器對於 IntersectionObserver 的支持度仍然較低,它不會再每個地方都正常工作,因此 W3C 對此開發了 polyfill 用來支援,當然 polyfill 效能就是比原生的還要差了。

#Intersection, Observer, IntersectionObserver API, Javascript, 交叉觀察器, lazy load, 懶加載, infinite scrolling, 無限捲動, setInterval

留言