ที่ผ่านมา สาย Optimize หรือ คนทำเว็บที่มีรูปเยอะๆ ก็มักที่จะใช้เทคนิค Lazy load กันทั้งนั้น ซึ่งต่างคนต่างก็จะมี Lib ที่ตัวเองถนัดต่างกันออกไป ตัวที่น่าจะฮิตที่สุดก็คงไม่พ้น ตัวนี้
verlok / vanilla-lazyload
LazyLoad is a lightweight, flexible script that speeds up your website by deferring the loading of your below-the-fold images, backgrounds, videos, iframes and scripts to when they will enter the viewport. Written in plain "vanilla" JavaScript, it leverages IntersectionObserver, supports responsive images and enables native lazy loading.
LazyLoad is a lightweight (2.4 kB) and flexible script that speeds up your web application by deferring the loading of your below-the-fold images, videos and iframes to when they will enter the viewport. It's written in plain "vanilla" JavaScript, it leverages the IntersectionObserver API, it supports responsive images, it optimizes your website for slower connections, and can enable native lazy loading. See notable features for more.
Love this project?
👨💻 Getting started - HTML
In order to make your content be loaded by LazyLoad, you must use some data-
attributes instead of the actual attributes. Examples below.
Lazy image:
<img
alt="A lazy image"
class="lazy"
…ซึงทุกคนก็คงรู้ว่า การใส่ Lib JS เข้าไป ถึงแม้จะทำให้ รูปโหลดเร็วขึ้น แต่เราก็ต้องแลกกับการมี Lib หนึ่งตัว ติดอยู่ใน Code ของเรา แต่เรื่องนี้มันกำลังจะจบลงในอีกไม่นานนี้ครับ เพราะว่า lazyload ที่เป็น native กำลังจะ Support ทุก Browser แล้ว!!!!!!
ตอนนี้ก็เหลือแค่ Safari เอา Feature นี้ออกจาก Experimental เท่านี้ เราก็จะใช้ LazyLoad ได้โดยไม่ต้องใช้ Lib อะไรแล้ว ส่วนใครที่สงสัยว่ามันใช้ยังไง วิธีก็ง่ายมากๆครับ เพียงแค่ เขียน Attribute loading=”lazy” ไว้ใน tag image หรือ Iframe ก็สามารถใช้งาน lazyload ได้เลย
<img src="https://example.org/image.jpg" width=”300” height=”200” loading=”lazy”>
<iframe src="https://example.org/" width=”300” height=”200” loading=”lazy”>
มีอยู่นิดเดียวที่ต้องรู้ก็คือ Image ที่จะใส่ Lazy load ต้องกำหนด ขนาดให้มันนะครับ ไม่อย่างนั้น Lazyload จะไม่ทำงานครับ
แล้วพอ feature นี้มันกลายเป็น Native เวลาที่ Browser Optimize อะไรก็จะส่งผลให้ Feature นี้ ทำงานได้ดีขึ้นไปอีกโดยที่เราไม่จำเป็นต้องไปปรับแต่งอะไรอย่างเช่น Chrome ที่มี Feature นี้มานานมากๆแล้ว ก็ได้ Optimize Feature นี้ไปบางส่วนแล้วเหมือนกัน
We’ve improved <img> lazy-loading in Chrome! bit.ly/lazy-updates The new thresholds for when we load <img loading=lazy>:
* Offer *much* better data-savings
* Are closer to JavaScript lazy-loading libraries
* Are rolling out to Chrome 79+07:00 AM - 17 Jul 2020
ก็เอาว่าใครยังไม่เคยลองใช้ก็ไปใช้ดูครับ ของดีๆที่ใช้ง่ายๆ
Top comments (0)