Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

javascript - Hide page until everything is loaded Advanced

I have a webpage which heavily makes use of jQuery.

My goal is to only show the page when everything is ready.

With that I want to avoid showing the annoying page rendering to the user.

I tried this so far (#body_holder is a wrapper inside body):

$(function(){
    $('#body_holder').hide();
});
$(window).load(function() {
    $("#body_holder").show();
});

This works completely fine, but messes up the layout.

The problem is that hiding the wrapper interferes with the other jQuery functions and plugins used (eg layout-plugin).

So I guess there must be another trick to do this. Maybe lay a picture or div over the body until window.load has occurred?

What approaches do you use?

EDIT:

The solution most likely has to be another way than display:none or hide();

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Anything done with jQuery will normally have to wait for document.ready, which is too late IMHO.

Put a div on top, like so:

<div id="cover"></div>

set some styles:

#cover {position: fixed; height: 100%; width: 100%; top:0; left: 0; background: #000; z-index:9999;}

and hide it with JS when all elements are loaded:

$(window).on('load', function() {
   $("#cover").hide();
});

Or if for some reason your script uses even longer time then the DOM elements to load, set an interval to check the type of some function that loads the slowest, and remove the cover when all functions are defined!

$(window).on('load', function() {
    $("#cover").fadeOut(200);
});

//stackoverflow does not fire the window onload properly, substituted with fake load

function newW()
{
    $(window).load();
}
setTimeout(newW, 1000);
#cover {position: fixed; height: 100%; width: 100%; top:0; left: 0; background: #000; z-index:9999; 
    font-size: 60px; text-align: center; padding-top: 200px; color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<ul>
    <li>This</li>
    <li>is</li>
    <li>a</li>
    <li>simple</li>
    <li>test</li>
    <li>of</li>
    <li>a</li>
    <li>cover</li>
</ul>

<div id="cover">LOADING</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...