LazyLoad 是一個輕量級 (2.4 kB) 且靈活的腳本,它透過將首屏圖像、動畫 SVG、視訊和 iframe 的載入推遲到它們進入視口的時間來加速 Web 應用程式。它是用普通的「vanilla」JavaScript 編寫的,它利用 IntersectionObserver API,它支援響應式圖像,它優化您的網站以降低連接速度,並且可以啟用本機延遲載入。查看所有功能以了解更多資訊。
➡️ 跳到: ? 入門 - HTML - ? 入門 - 劇本 - ?食譜 - 演示 - ?提示和技巧 - ? API-?所有功能比較
喜歡這個項目嗎? ?給我買杯咖啡吧!
為了讓您的內容能夠被 LazyLoad 加載,您必須使用一些data-
屬性而不是實際的屬性。下面的例子。
< img alt =" A lazy image " class =" lazy " data-src =" lazy.jpg " />
< img alt =" A lazy image " class =" lazy " src =" lazy-lowQuality.jpg " data-src =" lazy.jpg " />
srcset
和sizes
惰性響應圖像: < img
alt =" A lazy image "
class =" lazy "
data-src =" lazy.jpg "
data-srcset =" lazy_400.jpg 400w,
lazy_800.jpg 800w "
data-sizes =" 100w "
/>
若要使用低品質佔位符,請新增指向影像的非常小的版本的src
屬性。例如src="lazy_10.jpg"
。
picture
標籤支援高 dpi 的惰性響應圖像: < picture >
< source media =" (min-width: 1200px) " data-srcset =" lazy_1200.jpg 1x, lazy_2400.jpg 2x " />
< source media =" (min-width: 800px) " data-srcset =" lazy_800.jpg 1x, lazy_1600.jpg 2x " />
< img alt =" A lazy image " class =" lazy " data-src =" lazy.jpg " />
</ picture >
若要使用低品質佔位符,請將指向影像的非常小的版本的src
屬性新增至img
標記。例如src="lazy_10.jpg"
。
picture
標籤自動選擇WebP格式的惰性回應影像: < picture >
< source
type =" image/webp "
data-srcset =" lazy_400.webp 400w,
lazy_800.webp 800w "
data-sizes =" 100w "
/>
< img
alt =" A lazy image "
class =" lazy "
data-src =" lazy.jpg "
data-srcset =" lazy_400.jpg 400w,
lazy_800.jpg 800w "
data-sizes =" 100w "
/>
</ picture >
若要使用低品質佔位符,請將指向影像的非常小的版本的src
屬性新增至img
標記。例如src="lazy_10.jpg"
。
重要提示:若要在頁面上顯示內容圖像,請務必使用img
標籤。這將有利於搜尋引擎優化和網站的可訪問性。要了解您的圖像是內容還是背景,請問問自己:「我的網站使用者希望在列印頁面時看到這些圖像嗎?」。如果答案是“是”,那麼您的圖像就是內容圖像,您應該避免使用背景圖像來顯示它們。
< div class =" lazy " data-bg =" lazy.jpg " > </ div >
< div class =" lazy " data-bg =" lazy.jpg " data-bg-hidpi =" [email protected] " > </ div >
< div
class =" lazy "
data-bg-multi =" url(lazy-head.jpg),
url(lazy-body.jpg),
linear-gradient(#fff, #ccc) "
>
...
</ div >
< div
class =" lazy "
data-bg-multi =" url(lazy-head.jpg),
url(lazy-body.jpg),
linear-gradient(#fff, #ccc) "
data-bg-multi-hidpi =" url([email protected]),
url([email protected]),
linear-gradient(#fff, #ccc) "
>
...
</ div >
image-set
背景: < div class =" lazy " data-bg-set =" url('[email protected]') 1x, url('[email protected]') 2x " > ... </ div >
image-set
多個背景: < div
class =" lazy "
data-bg-set ="
url('[email protected]') 1x, url('[email protected]') 2x |
url('[email protected]') 1x, url('[email protected]') 2x
"
>
...
</ div >
< object class =" lazy " type =" image/svg+xml " data-src =" lazy.svg " > </ object >
< video class =" lazy " controls width =" 620 " data-src =" lazy.mp4 " data-poster =" lazy.jpg " >
< source type =" video/mp4 " data-src =" lazy.mp4 " />
< source type =" video/ogg " data-src =" lazy.ogg " />
< source type =" video/avi " data-src =" lazy.avi " />
</ video >
請注意,視頻海報也可以延遲加載。
< iframe class =" lazy " data-src =" lazyFrame.html " > </ iframe >
喜歡這個項目嗎? ?給我買杯咖啡吧!
LazyLoad 的最新推薦版本是19.1.3 。請注意,如果需要支援 Internet Explorer 11,則需要使用 17.9.0 或更低版本。
閱讀實用升級指南,快速了解如何從先前版本升級。
使用 LazyLoad 的最簡單方法是包含來自 CDN 的腳本。
< script src =" https://cdn.jsdelivr.net/npm/[email protected]/dist/lazyload.min.js " > </ script >
或者,如果您希望將其作為 ES 模組匯入:
< script type =" module " >
import LazyLoad from "https://cdn.jsdelivr.net/npm/[email protected]/+esm" ;
</ script >
然後,在您的 javascript 程式碼中:
var lazyLoadInstance = new LazyLoad ( {
// Your custom settings go here
} ) ;
為了確保在實例化 LazyLoad 時,惰性內容的 DOM 已準備就緒,請將腳本標記放在結束</body>
標記之前。
如果稍後有更多 DOM 到達,例如透過 AJAX 調用,您將需要調用lazyLoadInstance.update();
讓 LazyLoad 再次檢查 DOM。
lazyLoadInstance . update ( ) ;
async
腳本如果您願意,可以使用async
腳本包含 LazyLoad 的腳本,並在載入後立即對其進行初始化。
為此,您必須在包含腳本之前定義選項。您可以透過:
{}
一個對象,用於取得 LazyLoad 的單一實例[{}, {}]
一組對象,用於取得 LazyLoad 的多個實例,每個實例都有不同的選項。 < script >
// Set the options globally
// to make LazyLoad self-initialize
window . lazyLoadOptions = {
// Your custom settings go here
} ;
</ script >
然後包含腳本。
< script
async
src =" https://cdn.jsdelivr.net/npm/[email protected]/dist/lazyload.min.js "
> </ script >
可以將 script 標籤放在結束</body>
標籤之前。如果你做不到這一點,LazyLoad 可能會在瀏覽器載入所有 DOM 之前執行,並且你需要呼叫它的update()
方法以使其再次檢查 DOM。
async
腳本+取得實例引用與上面相同,但您必須在包含async
腳本之前放置如下所示的addEventListener
程式碼。
< script >
// Set the options globally
// to make LazyLoad self-initialize
window . lazyLoadOptions = {
// Your custom settings go here
} ;
// Listen to the initialization event
// and get the instance of LazyLoad
window . addEventListener (
"LazyLoad::Initialized" ,
function ( event ) {
window . lazyLoadInstance = event . detail . instance ;
} ,
false
) ;
</ script >
然後包含腳本。
< script
async
src =" https://cdn.jsdelivr.net/npm/[email protected]/dist/lazyload.min.js "
> </ script >
現在您將能夠呼叫它的方法,例如:
lazyLoadInstance . update ( ) ;
示範 - 來源 ← 對於單一 LazyLoad 實例
示範 - 來源 ← 用於多個 LazyLoad 實例
如果您希望在專案中本地安裝 LazyLoad,您可以!
npm install vanilla-lazyload
bower install vanilla-lazyload
下載最新版本之一。您需要的檔案位於dist
資料夾內。如果您不知道該選擇哪一個,請使用lazyload.min.js
,或閱讀有關捆綁包的資訊。
如果您在本機安裝 LazyLoad,則可以將其作為 ES 模組匯入,如下所示:
import LazyLoad from "vanilla-lazyload" ;
也可以(但不建議)使用require
commonJS 語法。
有關將 LazyLoad 與 WebPack 捆綁在一起的更多資訊可在此特定存儲庫中找到。
來看看在 Sandbox 上使用 React 和 LazyLoad 的範例。
此實作採用與通常傳遞給img
標籤相同的 props,但它呈現惰性圖像。請隨意分叉並改進它!
在dist
資料夾中,您會發現不同的捆綁包。
檔案名稱 | 模組類型 | 優點 |
---|---|---|
lazyload.min.js | UMD(通用模組定義) | 幾乎在任何地方都可以工作,甚至在 common-js 上下文中也是如此 |
lazyload.iife.min.js | IIFE(立即呼叫函數表達式) | 作為頁內<script src="..."> 運行,比 UMD 版本小 ~0.5kb |
esm/lazyload.js | ES模組 | 匯出LazyLoad ,以便您可以使用<script type="module" src="..."> 和 WebPack 或 Rollup 等捆綁器將其匯入專案中 |
喜歡這個項目嗎? ?給我買杯咖啡吧!
為了方便起見,您可以在此部分中找到複製和貼上程式碼的準備。
用例:當您延遲加載的圖像在加載之前顯示其
alt
文字和空圖像圖示。
CSS
img : not ([ src ]) : not ([ srcset ]) {
visibility : hidden;
}
就是這樣,真的。
使用案例:當您想防止在網站上顯示不存在/損壞的圖像時。
JavaScript
var myLazyLoad = new LazyLoad ( {
// Other options here...
callback_error : ( img ) => {
// Use the following line only if your images have the `srcset` attribute
img . setAttribute ( "srcset" , "[email protected] 1x, [email protected] 2x" ) ;
img . setAttribute ( "src" , "[email protected]" ) ;
}
} ) ;
注意:如果錯誤是由網路關閉(導航器暫時離線)產生的,vanilla-lazyload 將在網路再次可用時嘗試再次載入圖片。
範例 - API
用例:當你想要延遲載入圖像,但滾動區域中的圖像數量發生變化時,可能是因為它們是非同步添加的。
JavaScript
var myLazyLoad = new LazyLoad ( ) ;
// After your content has changed...
myLazyLoad . update ( ) ;
演示 - 來源 - API
使用案例:您希望使用
use_native
選項將圖像、iframe 和影片的載入委託給支援的瀏覽器引擎,但您也希望延遲載入背景圖像。
超文本標記語言
< img class =" lazy " alt =" A lazy image " data-src =" lazy.jpg " />
< iframe class =" lazy " data-src =" lazyFrame.html " > </ iframe >
< video class =" lazy " controls data-src =" lazy.mp4 " data-poster =" lazy.jpg " > ... </ video >
< object class =" lazy " type =" image/svg+xml " data-src =" lazy.svg " > </ object >
< div class =" lazy " data-bg =" lazy.jpg " > </ div >
JavaScript
// Instance using native lazy loading
const lazyContent = new LazyLoad ( {
use_native : true // <-- there you go
} ) ;
// Instance without native lazy loading
const lazyBackground = new LazyLoad ( {
// DON'T PASS use_native: true HERE
} ) ;
演示 - 來源 - API
使用案例:當您的滾動容器不是主瀏覽器窗口,而是滾動容器。
超文本標記語言
< div class =" scrollingPanel " >
<!-- Set of images -->
</ div >
JavaScript
var myLazyLoad = new LazyLoad ( {
container : document . querySelector ( ".scrollingPanel" )
} ) ;
演示 - 來源 - API
如果您有多個滾動面板,則可以使用以下標記和程式碼。
超文本標記語言
< div id =" scrollingPanel1 " class =" scrollingPanel " >
<!-- Set of images -->
</ div >
< div id =" scrollingPanel2 " class =" scrollingPanel " >
<!-- Set of images -->
</ div >
JavaScript
var myLazyLoad1 = new LazyLoad ( {
container : document . getElementById ( "scrollingPanel1" )
} ) ;
var myLazyLoad2 = new LazyLoad ( {
container : document . getElementById ( "scrollingPanel2" )
} ) ;
演示 - 來源 - API
使用案例:當給定元素進入視口時,您想要執行任意腳本或函數
超文本標記語言
< div class =" lazy " data-lazy-function =" foo " > ... </ div >
< div class =" lazy " data-lazy-function =" bar " > ... </ div >
< div class =" lazy " data-lazy-function =" buzz " > ... </ div >
< div class =" lazy " data-lazy-function =" booya " > ... </ div >
JS
// It's a best practice to scope the function names inside a namespace like `lazyFunctions`.
window . lazyFunctions = {
foo : function ( element ) {
element . style . color = "red" ;
console . log ( "foo" ) ;
} ,
bar : function ( element ) {
element . remove ( element ) ;
console . log ( "bar" ) ;
} ,
buzz : function ( element ) {
var span = document . createElement ( "span" ) ;
span . innerText = " - buzz!" ;
element . appendChild ( span ) ;
console . log ( "buzz" ) ;
} ,
booya : function ( element ) {
element . classList . add ( "boo" ) ;
console . log ( "booya" ) ;
}
} ;
function executeLazyFunction ( element ) {
var lazyFunctionName = element . getAttribute ( "data-lazy-function" ) ;
var lazyFunction = window . lazyFunctions [ lazyFunctionName ] ;
if ( ! lazyFunction ) return ;
lazyFunction ( element ) ;
}
var ll = new LazyLoad ( {
unobserve_entered : true , // <- Avoid executing the function multiple times
callback_enter : executeLazyFunction // Assigning the function defined above
} ) ;
使用unobserve_entered
以避免多次執行函數。
就是這樣。每當具有data-lazy-function
屬性的元素進入視口時,LazyLoad 都會呼叫executeLazyScript
函數,該函數從data-lazy-function
屬性本身取得函數名稱並執行它。
演示 - 來源 - API
使用案例:當您有很多水平滾動容器並且您想要在它們上實例化 LazyLoad 實例時,但僅當它們進入視口時。
超文本標記語言
< div class =" horizContainer " >
< img
src =""
alt =" Row 01, col 01 "
data-src =" https://placeholdit.imgix.net/~text?txtsize=19&txt=row_01_col_01&w=200&h=200 "
/>
< img
src =""
alt =" Row 01, col 02 "
data-src =" https://placeholdit.imgix.net/~text?txtsize=19&txt=row_01_col_02&w=200&h=200 "
/>
<!-- ... -->
</ div >
< div class =" horizContainer " >
< img
src =""
alt =" Row 02, col 01 "
data-src =" https://placeholdit.imgix.net/~text?txtsize=19&txt=row_02_col_01&w=200&h=200 "
/>
< img
src =""
alt =" Row 02, col 02 "
data-src =" https://placeholdit.imgix.net/~text?txtsize=19&txt=row_02_col_02&w=200&h=200 "
/>
<!-- ... -->
</ div >
JavaScript
var lazyLoadInstances = [ ] ;
var initOneLazyLoad = function ( horizContainerElement ) {
// When the .horizContainer element enters the viewport,
// instantiate a new LazyLoad on the horizContainerElement
var oneLL = new LazyLoad ( {
container : horizContainerElement
} ) ;
// Optionally push it in the lazyLoadInstances
// array to keep track of the instances
lazyLoadInstances . push ( oneLL ) ;
} ;
// The "lazyLazy" instance of lazyload is used to check
// when the .horizContainer divs enter the viewport
var lazyLazy = new LazyLoad ( {
elements_selector : ".horizContainer" ,
callback_enter : initOneLazyLoad ,
unobserve_entered : true // Stop observing .horizContainer(s) after they entered
} ) ;
就是這樣。每當.horizContainer
元素進入視口時,LazyLoad 都會呼叫initOneLazyLoad
函數,該函數會在.horizContainer
元素上建立 LazyLoad 的新實例。
演示 - 來源 - API
喜歡這個項目嗎? ?給我買杯咖啡吧!
沒有找到完全符合您情況的食譜?我們有演示!
demos 資料夾包含 30 多個 vanilla-lazyload 使用案例。您可能會在那裡找到您正在尋找的東西。
類型 | 標題 | 程式碼 | 示範 |
---|---|---|---|
內容 | 簡單的延遲載入圖像,不使用任何占位符 | 程式碼 | 居住 |
內容 | 使用內聯 SVG 作為佔位符的惰性圖像 | 程式碼 | 居住 |
內容 | 使用外部 SVG 檔案作為佔位符的惰性圖像 | 程式碼 | 居住 |
內容 | 使用srcset 的惰性響應圖像 | 程式碼 | 居住 |
內容 | 帶有<picture> 標籤和media 屬性的惰性響應圖像(藝術指導) | 程式碼 | 居住 |
內容 | 具有srcset 和sizes 惰性響應圖像(使用data-sizes ) | 程式碼 | 居住 |
內容 | 具有srcset 和sizes 的惰性響應圖像(使用普通sizes ) | 程式碼 | 居住 |
內容 | 具有多個<source> 標籤的惰性影片、不同的預載選項、無自動播放 | 程式碼 | 居住 |
內容 | 具有多個<source> 標籤、不同預載選項、帶自動播放的惰性視頻 | 程式碼 | 居住 |
內容 | 延遲載入背景圖像 | 程式碼 | 居住 |
內容 | 延遲載入多個背景圖像 | 程式碼 | 居住 |
內容 | 使用image-set() 延遲載入背景圖片 | 程式碼 | 居住 |
內容 | 延遲載入 iframe | 程式碼 | 居住 |
內容 | 延遲載入動畫 SVG 和 PDF 文件 | 程式碼 | 居住 |
內容 | 帶有<picture> 標籤和 WebP 的type 屬性的惰性 WebP 映像 | 程式碼 | 居住 |
載入中 | 使用<script async> 非同步載入 LazyLoad | 程式碼 | 居住 |
載入中 | 使用<script async> 非同步載入多個 LazyLoad 實例 | 程式碼 | 居住 |
錯誤 | 當restore_on_error 為false 時測試錯誤載入行為 | 程式碼 | 居住 |
錯誤 | 當restore_on_error 為true 時測試錯誤載入行為 | 程式碼 | 居住 |
科技 | 圖片載入時淡入淡出 | 程式碼 | 居住 |
科技 | 僅 CSS 水平滑桿中的延遲載入圖片(Netflix 風格) | 程式碼 | 居住 |
科技 | 延遲建立 Swiper 實例並延遲載入 Swiper 映像 | 程式碼 | 居住 |
科技 | 當特定元素進入視口時延遲執行函數 | 程式碼 | 居住 |
科技 | 如何管理包含惰性圖像的頁面的列印 | 程式碼 | 居住 |
科技 | 滾動容器中包含惰性影像的彈出層 | 程式碼 | 居住 |
設定 | 多個滾動容器 | 程式碼 | 居住 |
設定 | 單滾動容器 | 程式碼 | 居住 |
方法 | 如何將 DOM restore() 到原始狀態,和/或destroy() LazyLoad | 程式碼 | 居住 |
方法 | 加入動態內容,然後update() LazyLoad | 程式碼 | 居住 |
方法 | 加入動態內容,然後update() LazyLoad 傳遞元素的 NodeSet | 程式碼 | 居住 |
方法 | 使用load() 方法載入準時映像 | 程式碼 | 居住 |
方法 | 使用loadAll() 一次載入所有圖片 | 程式碼 | 居住 |
測試 | 測試多個閾值 | 程式碼 | 居住 |
測試 | 使用隱藏影像測試行為 | 程式碼 | 居住 |
測試 | 測試效能,懶加載上百張圖片 | 程式碼 | 居住 |
本國的 | 測試圖像的本機延遲加載,無需任何 javascript 行,甚至無需此腳本 | 程式碼 | 居住 |
本國的 | 使用use_native 選項有條件地測試圖像的本機延遲載入(請參閱 API) | 程式碼 | 居住 |
喜歡這個項目嗎? ?給我買杯咖啡吧!