Create a full-screen website pre-loader in a jiffy
阿新 • • 發佈:2018-12-29
Shall we, pre-load?
Important thing first, grab the latest jQuery CDN from here. In the HTML, we’ll have these:
- The CDN
<script>
tag inside the<head>
along with the style-sheet<link>
. - Inside the
<body>
we’ll make a<div>
withclass "loading-page”
- Make another
<div>
which contains the actual text. That is, a<h1>
and a<h2>
tag which says “LOADED…”. Let this be the counter class.
Let’s come to the styling part before we dive into jQuery. Make sure you style according to these:
- For the
body
, add abackground
color, give itwidth
height
of100vw
and100vh
receptively so that it covers the entire viewport. The must be set tohidden
. This is so that if the browser’s window is clipped, the content will be invisible. - For the
loading-page
class, add a lighterbackground
color than thebody
with samewidth
andheight
. - Next, for both the
loading-page
counter
’sh1
, add atop
andleft
of50%
with property set to-50%
for x and y-axes. Make sure thatfont-size
is300px
withbolder
weight and from top it’s-10px
in margin.
Here’s the jQuery part then,
- Use the function to make it available after the document is loaded.
- Add a
counter
variable and set it to0
. This will take in the count of the total percentage. Higher the number, lower the percentage. We’ll also need a secondary counter, let’s call itc
. This will be used later when we’ll increment the percent. - Take a variable, say
i
, use the function so that the following executes after a specific interval of time. - Select the
loading-page
andcounter h1
classes and use the function to get the secondaryc
counter element. - Now for the actual percentage, select only the
loading-page
class, use the function to get its specified CSS property by passing thewidth
and%
as its parameters so that it can calculate the total percent remaining to load. - Increment both the
c
andcounter
variables because, why not? - Now for the exception handling stuff, add an
if
condition. If thecounter
goes beyond100
, or is101
, then we can . - At last, for the
.ready()
’s time parameter, use a lower value like35
. More value will mean slow loading speed.
Time to save and run the code! You will get the same output provided that you followed each step. If now, here are some screenshots of the code:
HTML and jQuery code:
CSS code: