a shot of dev knowledge

RELATED TAGS

How to add a page loader to a web page

Introduction

A page loader is the display that is visible to the user of a website while the web page loads to the browser. If there is no page loader and the page takes a longer time to load than usual, the users of the site will be left with a blank white page.

This can be changed with a page loader, <div>, that you have designed to fit your needs.

How to create a page loader

To create a page loader, you simply need to:

  • Create your HTML code to indicate what you want to use as your loader, e.g., an image or an icon.
  • Then, style your loader page to your taste. One of the common choices among designers is to animate their loaders.
  • Finally, create a JavaScript script that will fire up when the page is requested and then execute the code it contains. In this case, the code will check if the page is not loaded and then display the loader if so.

Below is a sample page loader code.

Code

Try to click the run button multiple times to see the page loader effect.

Explanation

We create and style a loader, as well as the page to be displayed.

In JavaScript, when document.readyState changes, a readystatechange event happens and our function executes. This function holds that if the document is not yet loaded, then the body should remain hidden from the user, and only the loader should be visible.

Once the page has completely loaded, the loader is immediately set to display:none, and the body is made visible.

If the page doesn’t load quickly enough, the spinner below (which is our loader) will be visible. Due to how fast the page in the previous code loads, you can only see the loader for a short time.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring