欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于JavaScript+IntersectionObserver實(shí)現(xiàn)高性能圖片懶加載

 更新時(shí)間:2025年01月09日 11:47:57   作者:當(dāng)時(shí)只道尋常  
在 Web 開發(fā)中,圖片懶加載是一種常見的優(yōu)化手段,尤其在長列表頁面中,按需加載圖片可以顯著提升頁面性能,本篇文章將通過 JavaScript 和 Intersection Observer,實(shí)現(xiàn)一個(gè)帶有卡片樣式的高性能圖片懶加載示例,需要的朋友可以參考下

一、前言

在 Web 開發(fā)中,圖片懶加載是一種常見的優(yōu)化手段,尤其在長列表頁面中,按需加載圖片可以顯著提升頁面性能。本篇文章將通過 JavaScript 和 Intersection Observer,實(shí)現(xiàn)一個(gè)帶有卡片樣式的高性能圖片懶加載示例。

二、樣式布局

以下是卡片列表的樣式,采用了 CSS Grid 布局,支持響應(yīng)式排列,并為圖片卡片添加了縮放動畫效果:

body {
  background-color: #f5f6f7;
}

.card-list {
  --ap-gap: 16px; /* 列表項(xiàng)的間距 */
  --ap-min-width: 300px; /* 列表項(xiàng)的最小寬度 */
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(var(--ap-min-width), 1fr));
  gap: var(--ap-gap);
  padding: 16px;
}

.card-list .item {
  cursor: pointer;
  height: 497px;
  border-radius: 10px;
  box-shadow: 0 0 6px #000;
  overflow: hidden;
}

.card-list .item:hover img {
  transform: scale(1.5);
}

.card-list .item img {
  display: block;
  width: 100%;
  height: 100%;
  transition: all 0.32s;
}

上述樣式不僅定義了圖片卡片的基本外觀,還支持鼠標(biāo)懸停時(shí)的動態(tài)縮放效果,提升了用戶體驗(yàn)。

三、HTML 結(jié)構(gòu)

頁面結(jié)構(gòu)簡單明了,通過 JavaScript 動態(tài)生成卡片列表:

<div class="card-list"></div>

四、實(shí)現(xiàn)邏輯

1、配置項(xiàng)與生成圖片卡片

通過以下代碼,動態(tài)生成 99 張圖片卡片,使用默認(rèn)占位圖提高頁面加載速度:

const TOTAL_ITEMS = 99;
const DEFAULT_IMG = './img/default.jpg';
const IMG_URL_TEMPLATE = (index) => `https://picsum.photos/400/600?r=${index}`;

const cardList = document.querySelector('.card-list');

function generateItems() {
  const fragment = document.createDocumentFragment();
  for (let i = 0; i < TOTAL_ITEMS; i++) {
    const div = document.createElement('div');
    div.classList.add('item');
    const img = document.createElement('img');
    img.src = DEFAULT_IMG;
    img.dataset.src = IMG_URL_TEMPLATE(i);
    img.alt = `Image ${i + 1}`;
    div.appendChild(img);
    fragment.appendChild(div);
  }
  cardList.appendChild(fragment);
}
generateItems();

2、使用 Intersection Observer 實(shí)現(xiàn)懶加載

通過 Intersection Observer,可以高效檢測圖片是否進(jìn)入視口,并在合適的時(shí)機(jī)加載真實(shí)圖片:

function initLazyLoad() {
  const observer = new IntersectionObserver(
    (entries, observer) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return;
        const img = entry.target;
        img.src = img.dataset.src;
        observer.unobserve(img);
      });
    },
    { threshold: 0.01 }
  );

  document.querySelectorAll('img[data-src]').forEach((img) => observer.observe(img));
}
initLazyLoad();

本文通過樣式優(yōu)化和 Intersection Observer,有效提升了圖片懶加載的性能,同時(shí)保持了良好的用戶體驗(yàn)。這種實(shí)現(xiàn)方式不僅適用于圖片懶加載,也可以擴(kuò)展到其它按需加載場景,如視頻或組件加載。

到此這篇關(guān)于基于JavaScript+IntersectionObserver實(shí)現(xiàn)高性能圖片懶加載的文章就介紹到這了,更多相關(guān)JavaScript IntersectionObserver圖片懶加載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論