現代浏覽器原生支援使用 <img loading=lazy> 屬性進行延遲加載。 但是,如果頁面有布局偏移或無法靈活地指定頁面内所有圖像的寬度和高度,浏覽器将确定放錯位置的圖像對使用者可見并加載它們,這将損害頁面的整體性能。
Alpinejs 是一個功能強大且簡單的前端庫,可以使用一個 intersect 插件進行擴充,該插件将包裝 Intersection Observer,簡化元素進入視口時的反應方式。
安裝
import Alpine from 'alpinejs'
import intersect from '@alpinejs/intersect'
window.Alpine = Alpine
Alpine.plugin(intersect)
Alpine.start()
Alpine元件
通過将 x-data 指令添加到 div#lazy-loading-page 來建立一個元件,許多其他有用的指令可以用在它的孩子身上。 指令 x-intersect 可以添加到 Alpine 元件中的任何元素,當該元素進入視口(滾動到視圖)時,提供的加載圖像的表達式将執行。
<div x-data id="lazy-loading-page" class="h-full">
<section x-intersect.threshold.50="$refs.img1.src = $refs.img1.dataset.img" class="border-b-4 border-black p-8 h-full flex items-center justify-center">
<img
x-ref="img1"
class="opacity-0 transition-opacity duration-300 ease-linear"
src=""
data-img="https://via.placeholder.com/650x450"
onload="this.classList.add('opacity-100')"
/>
</section>
<section x-intersect.threshold.50="$refs.img2.src = $refs.img2.dataset.img" class="border-b-4 border-black p-8 h-full flex items-center justify-center">
<img
x-ref="img2"
class="opacity-0 transition-opacity duration-300 ease-linear"
src=""
data-img="https://via.placeholder.com/650x451"
onload="this.classList.add('opacity-100')"
/>
</section>
<section x-intersect.threshold.50="$refs.img3.src = $refs.img3.dataset.img" class="border-b-4 border-black p-8 h-full flex items-center justify-center">
<img
x-ref="img3"
class="opacity-0 transition-opacity duration-300 ease-linear"
src=""
data-img="https://via.placeholder.com/650x452"
onload="this.classList.add('opacity-100')"
/>
</section>
<section x-intersect.threshold.50="$refs.img4.src = $refs.img4.dataset.img" class="border-b-4 border-black p-8 h-full flex items-center justify-center">
<img
x-ref="img4"
class="opacity-0 transition-opacity duration-300 ease-linear"
src=""
data-img="https://via.placeholder.com/650x453"
onload="this.classList.add('opacity-100')"
/>
</section>
</div>
在上面的代碼中,x-intersect 指令與 .threshold 修飾符一起使用來控制底層 Intersection Observer 的門檻值屬性。 例如在一半元素進入頁面後觸發交叉,可以使用.threshold.50,這将執行表達式 $refs.img1.src = $refs.img1.dataset.img 來加載圖像。