DEV Community

Cover image for Create and implement a loader. (easy)
Ustariz Enzo
Ustariz Enzo

Posted on • Updated on

Create and implement a loader. (easy)

I hope that I'll help a lot of people with this one, creating a loader is so fun, and implementing it is easy as 1 2 3 !

If you prefer to watch the video version it's right here :

1. The animation

Create a basic div.

<div class="loader"></div>
Enter fullscreen mode Exit fullscreen mode

Style it, making it rounded, with a diffrent color on each side.

.loader {
    position: absolute;
    top: 40%;
    left: 50%;
    transform: translate(-50%,-50%);
    width: 200px;
    height: 200px;
    border: 20px solid;
    border-top-color: rgb(230, 62, 62);
    border-bottom-color: rgb(90, 204, 90);
    border-right-color: rgb(73, 52, 167);
    border-left-color: rgb(240, 203, 41);
    border-radius: 50%;
    animation: spin 2s infinite linear;
}
Enter fullscreen mode Exit fullscreen mode

Create the animation reffered in the last line of the above declaration.

@keyframes spin {
    from {
        transform: translate(-50%,-50%) rotate(0deg);
    }
    to {
        transform: translate(-50%,-50%) rotate(360deg);
    }
}
Enter fullscreen mode Exit fullscreen mode

Bravo ! 😎
You've just created your loading animation.
Now you want it to run when your website is loading ...

2. The JavaScript part

The first paint of your website will happen when the DOM is ready, not when every medias are fully loaded.
So you want your loader to run until everything is ready, until the "load" event is triggered.

First create a loader container that take the full screen :

<div class="loader-container">
    <div class="loader"></div>
</div>
Enter fullscreen mode Exit fullscreen mode
.loader-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: #000;
}
Enter fullscreen mode Exit fullscreen mode

Then simply show it while eveything is not fully loaded :

window.addEventListener('load', () => {
  document.querySelector('.loader-container').style.display ="none";
})
Enter fullscreen mode Exit fullscreen mode

And ... voilà ! 🥖🍷
A lovely loading effect.

Indeed if your website is empty, it will load very fast, but try to add some images and throttle down you connexion with the chrome devtools like i'm showing in the video, and you'll see the magic operate !

Source code, with all the shiny CSS is right here :
https://codepen.io/Ziratsu/pen/NWRYxWX

Come and take a look at my brand new Youtube channel :
https://www.youtube.com/c/TheWebSchool
Be the pioneer that follows me uh ? 😎

See you next time for some quick and polished tutorials !

Top comments (0)