How to Show a Loader Until the Fetch API Has Finished Loading the Page

image

is it loading or …

I recently shared my completed vanilla JavaScript and Rails project. That’s freshly deployed both on Heroku for the Rails backend and github.io for the frontend.

However, my friend was confused about my project because nothing was loading except for a few buttons. I had to tell her that she needed to wait for about 30 seconds to 5 minutes depending on how recently the app had been fetched. This was a problem that I needed to solve. What if my users weren’t informed and had no patience to wait for the data to load? There wasn’t even a sign that the data would load slowly.

I brainstormed and researched and I found a simple solution to this problem — adding a loader until the backend data gets fetched completely. I would like to share how to implement the loader with you in this article.

image

loading cat meme

image

This is the finished product with the clock emoji loader

<div class="preload">
  <div class="emoji">🕐</div>
</div>

create parent-child div in index.html

First, we need to create one parent div and one child div — a total of two div tags in index.html, where we want to locate the loader. It’s the best to place the div tag inside of the body. We will call the class of the parent div, preload , and the child div, emoji.

/********************** loader ***********************/

const loader = document.querySelector(".preload");

const emoji = loader.querySelector(".emoji");

const emojis = [
  "🕐",
  "🕜",
  "🕑",
  "🕝",
  "🕒",
  "🕞",
  "🕓",
  "🕟",
  "🕔",
  "🕠",
  "🕕",
  "🕡",
  "🕖",
  "🕢",
  "🕗",
  "🕣",
  "🕘",
  "🕤",
  "🕙",
  "🕥",
  "🕚",
  "🕦",
  "🕛",
  "🕧",
];

const interval = 125;

const loadEmojis = (arr) => {
  setInterval(() => {
    emoji.innerText = arr[Math.floor(Math.random() * arr.length)];

    //console.log(Math.floor(Math.random() * arr.length))
  }, interval);
};

const init = () => {
  loadEmojis(emojis);
};

init();

index.js

Then, we write the logic for the div tags in the index.js. First, let’s create two variables so we can easily select the elements in HTML. One, selecting the div class called preload, and the other, selecting emoji.

We will also create an array called emojis where we’re locating individual clock emojis as string values as individual element. setInterval logic will call the function with a fixed time delay between each call. In line 7, we will declare the interval as 125milliseconds. You can change the number however you would like the delay to be.

We will use the single responsibility principle and write two helper functions, loadEmojis and init. First, let’s call the function init in line 19. The init function located in line 16, takes the emojis array as an argument for the function loadEmojis. So we traverse to line 9, which utilizes the setInterval logic.

emoji.innerText = arr [ Math.floor ( Math.random() * arr.length ) ]

For line 11, let’s break it down. emoji.innerText is line 3, the emoji div. We will replace the emoji div with one of the clock emoji elements in the emojis array.

Math.random() function returns a floating-point, pseudo-random number in the range 0 to less than 1, for example 0.742. Then we will multiply the random number with the arr.length then use the Math.floor() to return the largest integer less than or equal to the given number so it’s any number less than the arr.length and larger than 0. This logic will let the clock emojis to continuously change so it looks like it’s loading.

image

Congratulations! Now you have the loader on the page! But wait. This is not what we want. We need to stop the loader when the data is being fetched from the backend. Here is the one-liner code that solves the problem.

/****************** FETCH Initial Render ******************/

fetch(request)
  .then((r) => r.json())

  .then((data) => {
    // console.log(data)

    document.querySelector(".preload").style.display = "none"; //stop the load
  });

loader stopper inside of the fetch

We will fetch the backend data and parse it. When the data gets fetched, then we will stop the loader so the location where we change the display logic is in line 6.

document.querySelector(“.preload”).style.display = “none”//stop the load

If you are not fetching, you can just place the line after calling the init function, so below the init(). Simply reassigning the style.display to “none” stops the loader.

Nice work! We hope you now feel like you have a decent grasp of how to implement the loader and how to stop it. Now your users are informed that if there’s a loader, the data is still loading.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics