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

如何实现返回首页时不显示加载页(加载页代码在首页文件中)

实现首页仅首次/刷新显示加载页的方案

要满足仅首次打开/刷新首页显示加载页,从站内其他页面返回时不显示的需求,可通过状态标记或来源判断实现,具体修改如下:

1. 核心修改:JavaScript逻辑(main.js)

替换原有加载触发代码,加入场景判断逻辑:

// 判断当前是否为首页
const isHomePage = window.location.pathname === '/' || window.location.pathname === '/index.html';
// 读取会话存储的首页访问标记
const hasVisitedHome = sessionStorage.getItem('hasVisitedHome');

if (isHomePage && !hasVisitedHome) {
  // 标记用户已访问过首页
  sessionStorage.setItem('hasVisitedHome', 'true');
  
  // 执行加载页动画逻辑
  $(window).on('load', function() {
    $('main').removeClass('hide');
    $(".loader").animate({'top': '-100%'});
    setTimeout(removeLoader, 2000);
  });
} else if (isHomePage) {
  // 从站内返回首页,直接显示内容并移除加载页
  $('.loader').remove();
  $('main').removeClass('hide');
}

function removeLoader(){
  $( ".loader" ).fadeOut(500, function() {
    $( ".loader" ).remove(); 
  });
}

2. 可选优化:CSS调整

为避免页面初始闪烁,给加载器添加默认隐藏样式:

.loader {
  /* 保留原有所有样式 */
  display: none; /* 添加这行默认隐藏 */
}

3. 逻辑说明

  • 会话存储标记:首次进入首页时存储hasVisitedHome标记,浏览器会话未结束(未关闭标签页)时标记持续有效,从站内其他页面返回首页时会读取到标记,跳过加载页。
  • 页面路径判断:仅在首页路径下执行加载页逻辑,其他页面完全不受影响。
  • 刷新兼容:用户刷新首页时,会话存储标记会被清除,重新触发加载页,符合需求。

替代方案:通过来源页面判断

若不想使用会话存储,可通过document.referrer判断来源是否为站内页面:

const isHomePage = window.location.pathname === '/' || window.location.pathname === '/index.html';
const isInternalReferrer = document.referrer.includes(window.location.origin);

if (isHomePage && !isInternalReferrer) {
  // 从外部进入或刷新首页,显示加载页
  $(window).on('load', function() {
    $('main').removeClass('hide');
    $(".loader").animate({'top': '-100%'});
    setTimeout(removeLoader, 2000);
  });
} else if (isHomePage) {
  // 从站内返回,直接显示内容
  $('.loader').remove();
  $('main').removeClass('hide');
}

该方案无需存储状态,刷新首页时document.referrer为空,仍会触发加载页,同样满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:03:23