You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Main.js导致页面崩溃:多页站仅首页加预载器其他页报textContent空值错误

错误原因

  1. 你的main.js被引入到了所有页面中,只有首页存在preLoader相关的DOM结构,其他页面执行document.querySelector('.preLoader')、document.querySelector('.preLoader .count')时会返回null,调用null的textContent属性就会触发你遇到的类型错误。
  2. 额外逻辑问题:你代码中let time = window.onload是错误写法,window.onload是页面加载完成的事件回调函数,将函数作为参数传给setInterval的第二个参数(要求为毫秒数值)时,会被转为NaN,最终定时器会按最小间隔执行,预载器进度会跳动异常。

修复方案

方案1(通用适配所有页面,无需拆分JS文件)

在loader函数开头先判断DOM元素是否存在,不存在就直接终止函数执行,同时修正定时器延迟参数:

function loader(success) {
  // 不存在预载器元素直接退出,避免非首页报错
  const preLoader = document.querySelector('.preLoader');
  const countEle = document.querySelector('.preLoader .count');
  if (!preLoader || !countEle) return;

  document.body.style.overflowY = 'hidden';
  // 可自定义定时器间隔,10ms的话100次就是1秒完成加载,根据需求调整数值
  const intervalTime = 10;
  let w = 0;
  const t = setInterval(function() {
    w++;
    countEle.textContent = w + '%';
    if (w > 99) {
      preLoader.classList.add('loaded');
      document.body.style.overflowY = 'auto';
      clearInterval(t);
      w = 0;
      success && success(t);
    }
  }, intervalTime);
}
loader();

方案2(仅首页执行预载器,性能更优)

给首页的<body>标签添加专属类名,比如class="index-page",调用loader前先判断是否为首页:

// 仅首页执行预载器逻辑
if (document.body.classList.contains('index-page')) {
  loader();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 18:42:02