1. 程式人生 > >Create a full-screen website pre-loader in a jiffy

Create a full-screen website pre-loader in a jiffy

Shall we, pre-load?

Let’s do a left to right load! GIF credits: GIPHY

Important thing first, grab the latest jQuery CDN from here. In the HTML, we’ll have these:

  1. The CDN <script> tag inside the <head> along with the style-sheet <link>.
  2. Inside the <body> we’ll make a <div> with class "loading-page”
    .
  3. 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:

  1. For the body, add a background color, give it width
    and height of 100vwand 100vh receptively so that it covers the entire viewport. The must be set to hidden. This is so that if the browser’s window is clipped, the content will be invisible.
  2. For the loading-page class, add a lighter background color than the bodywith same width and height.
  3. Next, for both the loading-page
    and counter’s h1, add a top and leftof 50% with property set to -50% for x and y-axes. Make sure that font-size is 300px with bolder weight and from top it’s -10px in margin.

Here’s the jQuery part then,

  1. Use the  function to make it available after the document is loaded.
  2. Add a counter variable and set it to 0. 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 it c. This will be used later when we’ll increment the percent.
  3. Take a variable, say i, use the function so that the following executes after a specific interval of time.
  4. Select the loading-page and counter h1 classes and use the function to get the secondary c counter element.
  5. Now for the actual percentage, select only the loading-page class, use the  function to get its specified CSS property by passing the widthand % as its parameters so that it can calculate the total percent remaining to load.
  6. Increment both the c and counter variables because, why not?
  7. Now for the exception handling stuff, add an if condition. If the countergoes beyond 100, or is 101, then we can .
  8. At last, for the .ready()’s time parameter, use a lower value like 35. 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: