管理杂谈OA答疑ERP答疑教程搜索

不要再用img标签展示图片了


在前端开发中,img标签 是一个比较常用的HTM元素,使用起来也比较方便,在很长一段时间里 img标签都是用来展示图片最直接有效的方式!但是img标签有着非常显著的弊端。

一、传统 <img> 标签的弊端

1. 性能问题

<!-- 直接阻塞渲染的典型示例 -->img src="large-image.jpg" <!-- 大图未优化 -->

2. 响应式局限

<!-- 需要复杂配置 -->img   srcset="image-320w.jpg 320w,          image-480w.jpg 480w"  sizes="(max-width: 600px) 480px, 100vw"

3. 体验缺陷

<!-- 缺少必要属性 -->img src="product.jpg" <!-- 无 alt 文本 -->

二、4种替代img标签方案


1. <picture> 元素

<picture>  <source     media="(min-width: 1200px)"    srcset="large.webp 1x, large@2x.webp 2x"    type="image/webp"  <source    srcset="medium.jpg 1x, medium@2x.jpg 2x"    type="image/jpeg"  <img     src="fallback.jpg"     alt="Responsive image"    loading="lazy"</picture>


2. CSS 背景图方案

.card {  background-imageurl('placeholder.svg');  background-size: cover;  position: relative;}
/* 通过媒体查询加载响应式图片 */@media (min-resolution2dppx) {  .card {    background-imageurl('image@2x.jpg');  }}
/* 使用伪元素实现渐进加载 */.card::after {  content'';  position: absolute;  inset: 0;  backgroundurl('image.jpg') no-repeat center/cover;  opacity0;  transition: opacity 0.3s;}
.card.loaded::after {  opacity1;}

优势:

// 使用 IntersectionObserver APIconst observer = new IntersectionObserver((entries) => {  entries.forEach(entry => {    if (entry.isIntersecting) {      const img = entry.target;      img.src = img.dataset.src;      observer.unobserve(img);    }  });});
document.querySelectorAll('[data-src]').forEach(img => {  observer.observe(img);});

4. SVG 矢量方案

<!-- 替代简单图标类图片 -->svg viewBox="0 0 24 24" class="icon"  path d="M12 2L3 9v12h18V9l-9-7z"/></svg
<!-- 动态颜色控制 -->svg class="icon" style="color: var(--theme-color);"  use href="sprite.svg#logo"></use</svg

优势:

三、最佳实践


1.格式选择策略

<picture>  <source type="image/avif" srcset="image.avif"  <source type="image/webp" srcset="image.webp"  <img src="image.jpg" alt="fallback"</picture>

2.尺寸优化原则


img   src="image.jpg"  width="800"  height="600"  style="max-width: 100%; height: auto;"  alt="Responsive image"

3.加载性能优化

new IntersectionObserver(entries => {/*...*/}, {  rootMargin'200px' // 提前 200px 加载});

合理选择图片加载方案可以实现:

阅读原文:原文链接


更多精彩文章浏览...
点击右上角图标分享到朋友圈
官方网站:http://www.clicksun.cn
咨询热线:400-186-1886
服务邮箱:service@clicksun.cn