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

如何实现仅特定场景显示Preloader,页面内跳转时不显示?

实现符合条件的Preloader加载页

完全可以实现你要的效果,先说说你之前两次尝试的问题:

  • 第一次用sessionStorage.setItem('doNotShow', true),一旦设置后刷新页面这个值还存在,导致刷新时不显示加载页,不符合需求。
  • 第二次默认直接显示加载页,点击链接仅临时隐藏,但跳转后的新页面仍会加载并显示加载页,达不到“站内跳转不显示”的目的。

核心思路

要精准区分两种场景:

  1. 需要显示加载页:首次进入、刷新页面、重新打开标签页、空白页打开网址——这些场景都属于从头加载页面,并非从站内链接跳转而来。
  2. 不需要显示:站内页面跳转——此时提前在sessionStorage中标记状态,告诉新页面“我是站内跳转过来的,无需显示加载页”。

修改后的完整代码

HTML

<center id="splashscreen">
    <img id="splashcontent" src="https://www.w3schools.com/html/pic_trulli.jpg">
</center>

CSS

#splashscreen {
    background-color: white;
    width: 100%;
    height: 100vh;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 998;
    cursor: pointer;
    visibility: hidden;
    opacity: 0;
    transition: visibility 0s, opacity 0.5s ease; /* 增加过渡动画提升体验 */
}
#splashscreen.show {
    visibility: visible;
    opacity: 1;
}
#splashcontent {
    max-width: 400px;
    width: 100%;
    height: auto;
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

jQuery 代码

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    const preloader = $("#splashscreen");
    const isInternalNav = sessionStorage.getItem('isInternalNavigation');

    // 加载页显示与点击逻辑
    function initPreloader() {
        preloader.addClass('show');
        $('html, body').css({ 'overflow': 'hidden' });
        
        preloader.click(function(){
            $(this).fadeOut(500, function() {
                $('html, body').css({ 'overflow': 'auto' });
            });
        });
    }

    // 判断是否需要显示加载页
    const navEntry = performance.getEntriesByType('navigation')[0];
    // 刷新页面,或首次进入/重新打开(且非站内跳转)时显示
    if (navEntry.type === 'reload' || (!isInternalNav && navEntry.type === 'navigate')) {
        initPreloader();
    } else {
        // 站内跳转直接移除加载页
        preloader.remove();
    }

    // 清除标记,避免影响下次刷新
    sessionStorage.removeItem('isInternalNavigation');

    // 监听站内链接点击,设置跳转标记
    $('a').click(function(e) {
        // 验证是否为同域名站内链接
        const linkUrl = new URL($(this).attr('href'), window.location.origin);
        if (linkUrl.origin === window.location.origin) {
            sessionStorage.setItem('isInternalNavigation', 'true');
        }
    });
});
</script>

代码说明

  1. 导航类型判断:通过performance.getEntriesByType('navigation')[0].type识别页面加载方式:
    • reload:页面由刷新触发
    • navigate:正常导航(首次进入、重新打开、空白页打开)
  2. 站内跳转标记:点击站内链接时,给sessionStorage设置标记,新页面加载时检测到标记则不显示加载页,随后立即清除标记,确保下次刷新时正常显示。
  3. 平滑过渡:CSS中添加transition属性,让加载页的显示/隐藏动画更流畅。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 07:54:18