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
361 views
in Technique[技术] by (71.8m points)

javascript - How can I display a loading gif until an entire html page has been loaded

I have a webpage that's pretty intensive via HTML and CSS, which leads to some elements loading faster then others when a user visits the page. The background may take awhile to load, and so on... It gets pretty ugly seeing it all load element by element...

So I'm wondering how I can first load a different page (page1, that has simply a gif and bare minimals of html) and then page2 (page with intensive html) will appear only after the client's browser has fetched all of the pages html.

I believe this can be done with JQuery, which I know almost nothing about...

Any advice would be appreciated, Thanks,

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Use the following HTML (at the top of the body is best):

<div id="loading"></div>

And this CSS:

#loading {
    background: url('spinner.gif') no-repeat center center;
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    z-index: 9999999;
}

And the following JavaScript (uses jQuery):

function hideLoader() {
    $('#loading').hide();
}

$(window).ready(hideLoader);

// Strongly recommended: Hide loader after 20 seconds, even if the page hasn't finished loading
setTimeout(hideLoader, 20 * 1000);

You could put the styles inline on the div instead of in a stylesheet for less chance of a flash of content before the loader. Also, you could use https://www.askapache.com/online-tools/base64-image-converter/ or a similar tool to convert your GIF to a base 64 URI, and use that instead of spinner.gif.


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

...