You need to enable JavaScript to run this app. 如何使用循环精简JavaScript 实现响应式背景图懒加载的代码重构
优惠活动
大模型
产品
解决方案
定价
更多

如何使用循环精简JavaScript 实现响应式背景图懒加载的代码重构

测试代码Bug原因

你编写的循环测试逻辑输出frameVariables[0]为null,问题出在两点:

  • 循环从i=0开始匹配id="frame0",但DOM元素id是从frame1开始编号,不存在该元素
  • 循环条件用了i <= FramesQuantity,比如匹配到5个.frame元素时,会多遍历一次查找不存在的id,完全没必要按id做选择器
    核心优化方向:不需要逐个通过id匹配元素,直接用类选择器批量获取所有.frame.lazy元素即可,天然适配任意数量的同结构元素
重构方案
  1. 移除所有重复的getElementById声明,直接通过document.querySelectorAll('.frame.lazy')批量获取所有目标元素
  2. 把所有标注REFACTOR LIST的重复DOM操作,全部收敛到单轮元素遍历中执行
  3. 保留原有响应式尺寸判断、跨断点才重新加载图片的性能逻辑,不改变原有功能
重构后完整代码

JS部分

// 直接批量获取所有带frame和lazy类的元素,无需逐个绑定id
const frameElements = document.querySelectorAll('.frame.lazy');

// 创建懒加载实例
var myLazyLoad = new LazyLoad({
  elements_selector: ".lazy"
});

// 响应式加载图片逻辑
function loadImgs() {
  console.log('Loading images...');
  // 单次计算当前视口尺寸,减少重复判断
  const isMobile = window.matchMedia("only screen and (max-width:700px)").matches;
  const srcAttr = isMobile ? 'data-src-small' : 'data-src-large';

  // 循环处理所有元素,替代原5组重复DOM操作
  frameElements.forEach(frame => {
    // 从对应尺寸的data属性取图片路径
    const targetSrc = frame.getAttribute(srcAttr);
    // 设置懒加载需要的data-src属性
    frame.setAttribute('data-src', targetSrc);
    // 移除已处理标记,让懒加载重新识别元素
    frame.removeAttribute('data-was-processed');
  })

  // 通知懒加载实例更新元素状态
  myLazyLoad.update();
}

// 首次加载执行图片匹配逻辑
loadImgs();

// 仅当视口尺寸跨越700px断点时才重新加载图片
var lastWindowSize = window.innerWidth;
window.onresize = function(event) {
    var currentWindowSize = window.innerWidth; 
    if((lastWindowSize <= 700 && currentWindowSize > 700) || (lastWindowSize > 700 && currentWindowSize <= 700)) {
      loadImgs();
    }
    lastWindowSize = currentWindowSize;
};

兼容提示:如果需要兼容IE等不支持ES6的浏览器,可以把forEach替换为普通for循环遍历frameElements列表,把const替换为var即可

原有CSS无需修改

html {
  box-sizing: border-box;
}

*, *::before, *::after {
  box-sizing: inherit;
  &:focus {
    outline: none;
  }
}

* {
  font-family: monaco, courier;
}

body {
  margin: 0;
  padding: 0;
}

.wrapper {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center ;
  background: #ddd;
}

p {
  position: absolute;
  top: 0;
  left: 0;
  margin: 0;
  padding: 8px;
  color: darkslategray;
  background: gold;
}

.frame {
  width: 80vw;
  height: 200px;
  margin: 0 0 1rem 0;
  padding: 0;
  position: relative;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  border: 2px solid gold;
}

HTML可简化(无需保留id属性)

原代码中引入的jQuery未被使用,可直接删除该脚本标签减少加载体积

<script src="https://cdnjs.cloudflare.com/ajax/libs/vanilla-lazyload/8.7.1/lazyload.min.js"></script>

<main class="wrapper">
  <a href="#">
    <div class="frame lazy" 
      data-src-small="https://source.unsplash.com/random/400x200?sig=1"
      data-src-large="https://source.unsplash.com/random/1200x600?sig=1">
      <p>1</p>
    </div>
  </a>

  <a href="#">
    <div class="frame lazy" 
      data-src-small="https://source.unsplash.com/random/400x200?sig=2"
      data-src-large="https://source.unsplash.com/random/1200x600?sig=2">
      <p>2</p>
    </div>
  </a>

  <a href="#">
    <div class="frame lazy" 
      data-src-small="https://source.unsplash.com/random/400x200?sig=3"
      data-src-large="https://source.unsplash.com/random/1200x600?sig=3">
      <p>3</p>
    </div>
  </a>

  <a href="#">
    <div class="frame lazy" 
      data-src-small="https://source.unsplash.com/random/400x200?sig=4"
      data-src-large="https://source.unsplash.com/random/1200x600?sig=4">
      <p>4</p>
    </div>
  </a>

  <a href="#">
    <div class="frame lazy" 
      data-src-small="https://source.unsplash.com/random/400x200?sig=5"
      data-src-large="https://source.unsplash.com/random/1200x600?sig=5">
      <p>5</p>
    </div>
  </a>
</main>
适配特性说明
  • 无论后续新增多少个带frame lazy类的div,不需要修改任何JS代码,逻辑会自动遍历处理新增的元素
  • 原5组重复的DOM操作全部收敛为单循环,无冗余代码
  • 保留跨断点才重新加载的性能逻辑,不会因频繁resize触发多余图片请求

内容的提问来源于stack exchange,提问作者Chris_Heu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.15 03:36:04