Div显示至少1秒,或直到加载主要内容(以先到者为准)

Div display for a minimum of 1s, or until the main content is loaded - whichever comes first

本文关键字:显示 1秒 加载 Div      更新时间:2023-09-26

我已经实现了以下脚本,该脚本确保在我的网站主页上显示预加载页面,直到主页内容完全加载。

我想调整以下内容,以确保预加载程序始终显示最短的时间(即1s),以确保它始终显示,即使在快速连接时也是如此。预加载程序应该至少显示1秒,或者直到加载了主要内容——以先到者为准。这可能吗?

HTML

<div class='preloader'>
    <div class="preloader-logo">Logo</div>
    <div class="preloader-loading-icon">Loading</div>
</div>
<main>Content goes here, should be hidden initially until fully loaded (or 1s have lapsed).</main>

JS

/* Preloader Splash */
$(window).load(function(){
    $('main').animate({opacity: 1},300);
    $('.preloader').fadeOut(500);
});

CSS

.preloader {
    display: block;
    position: fixed;
    width: 100%;
    height: 100%;
    overflow: hidden;
    top: 0;
    left: 0;
    z-index: 9999;
    background: rgba(255,102,51,1);
}
.preloader-logo {
    background: url(images/ui-sprite.svg) no-repeat 0 -300px;
    position: absolute;
    width: 140px;
    height: 58px;
    top: 50%;
    left: 50%;
    text-indent: -9999px;
}
.preloader-loading-icon {
    background: url(images/preloader-loading.svg) no-repeat 50%;
    text-indent: -9999px;
    position: relative;
    top: 50%;
    left: 50%;
    margin-top: 90px;
    width: 40px;
    height: 40px;
}

我不确定我喜欢这个,但它是实现您想要的目标的简单方法:

var timedOut = false;
var loaded = false;
/* Preloader Splash */
$(window).load(function(){
    loaded = true;
    hideLoading();
});
setTimeout(function(){
    timedOut = true;
    hideLoading();
}, 1000);
function hideLoading(){
    if(loaded && timedOut){
        $('#container').animate({opacity: 1},300);
        $('.preloader').fadeOut(500);
    }
}

这意味着只有当1s已经通过时,加载才会隐藏加载,而如果页面已经加载,1s将关闭加载。

原始答案:

页面加载完成后,您可以将其显示1s:

/* Preloader Splash */
$(window).load(function(){
    setTimeout(function(){
        $('#container').animate({opacity: 1},300);
        $('.preloader').fadeOut(500);
    , 1000);
});

可能有更好的方法,因为这意味着即使在加载缓慢的页面上,完成加载后也会是1s,而不是直接加载。因此加载时间+1s,而不是加载时间或1s

最初,您的主要内容#container不透明度应设置为0,以便动画可以显示任何效果。

$(window).load(function(){
    // Code here executes when the whole content (with images etc) is loaded
});