Якщо ви нещодавно були в Інтернеті, швидше за все, ви бачили приємну витончену анімацію завантаження, яка заповнює вміст сторінки перед витонченим завантаженням.
Деякі соціальні гіганти, такі як Facebook, навіть використовують такий підхід, щоб покращити завантаження сторінок. Як ми можемо зробити це за допомогою простого CSS?
- Що ми будемо будувати?
- Просто потрібно фрагмент?
- Частина 1: Створення нашої анімації завантаження
- Частина 2: Використання нашої анімації завантаження в динамічному додатку
Що ми будемо будувати?
Ми збираємося створити завантажувальну анімацію, використовуючи клас CSS, який ви можете застосувати до майже будь-якого елемента, який хочете (в межах розумних причин).

Це дає вам велику гнучкість у використанні та робить рішення приємним та простим лише за допомогою CSS.
Незважаючи на те, що фрагмент досить маленький, і ви можете просто скопіювати та вставити його, я розповім вам, що відбувається, і приклад його динамічного використання під час завантаження даних.
Просто потрібно фрагмент?
Ви можете захопити його тут!
CSS завантаження анімації CSS завантаження анімації. GitHub Gist: миттєво діліться кодом, нотатками та фрагментами.

Чи потрібно мені знати, як анімувати перед цим підручником?
Немає! Ми детально розглянемо, що саме вам потрібно зробити. Насправді анімація в цьому посібнику порівняно проста, тому давайте копатись!
Частина 1: Створення нашої анімації завантаження
У цій першій частині основна увага приділяється об’єднанню анімації завантаження та її перегляду на статичному веб-сайті HTML. Мета полягає в тому, щоб пройти фактично створення фрагмента. Для цієї частини ми використовуватимемо лише HTML та CSS.
Крок 1: Створення зразка вмісту
Для початку ми хочемо трохи зразка вмісту. Тут насправді немає обмежень, ви можете створити це за допомогою базових HTML та CSS або додати це у свій додаток Create React!
Для прогулянки я буду використовувати HTML і CSS з кількома прикладами вмісту, які дозволять нам побачити це насправді.
Для початку створіть новий файл HTML. Всередині цього файлу HTML заповніть його деяким вмістом, який дасть нам можливість грати з нашою анімацією. Я збираюся використати фільлераму, яка використовує рядки мого улюбленого телешоу Futurama!

Якщо ви збираєтеся піти разом зі мною, ось як виглядає мій проект:
my-css-loading-animation-static - index.html - main.css
Слідуйте разом із комітом!
Крок 2: Починаючи з класу завантаження фундаменту
Для нашого фундаменту давайте створимо новий клас CSS. Всередині нашого CSS-файлу додамо:
.loading { background: #eceff1; }
За допомогою цього класу давайте додамо його до кількох або всіх наших елементів. Я додав його до кількох абзаців, заголовків та списків.
For example...

Це дає нам базовий фон, але ми, мабуть, хотіли б приховати цей текст. Коли він завантажується, ми ще не матимемо цього тексту, тому, швидше за все, ми хотіли б використовувати текст заливки або фіксовану висоту. У будь-якому випадку ми можемо встановити колір прозорим:
.loading { color: transparent; background: #eceff1; }

Якщо ви помітили з елементами списку, чи застосовуєте ви клас до елемента списку верхнього рівня (

Original text
- або
), це схоже на один великий блок. Якщо додати трохи поля внизу всіх елементів списку, ми можемо побачити інше в тому, як вони відображаються:
li { margin-bottom: .5em; }
І зараз воно починає об’єднуватися, але це виглядає просто як заповнювачі. Тож давайте анімуємо це, щоб виглядати так, ніби це насправді завантажується.
Слідуйте разом із комітом!
Крок 3: Стиль та анімація нашого класу завантаження
Перш ніж насправді анімувати наш клас, нам потрібно щось анімувати, тому давайте додамо градієнт до нашого
.loading
класу:.loading { color: transparent; background: linear-gradient(100deg, #eceff1 30%, #f6f7f8 50%, #eceff1 70%); }
Це означає, що ми хочемо лінійного градієнта, який нахилений на 100 градусів, де ми починаємо з
#eceff1
і згасаємо до#f6f7f8
30% і назад до#eceff1
70%;Спочатку важко розгледіти, коли воно все ще, це може просто виглядати як відблиски на вашому комп’ютері! Якщо ви хочете побачити його перед тим, як рухатись далі, сміливо грайте з кольорами вище, щоб побачити градієнт.
Тепер, коли нам є що анімувати, спочатку нам потрібно створити правило ключових кадрів:
@keyframes loading { 0% { background-position: 100% 50%; } 100% { background-position: 0 50%; } }
Це правило при застосуванні змінить фонове положення із початку на 100% від осі х до 0% від осі х.
За правилом, ми можемо додати властивість анімації до нашого
.loading
класу:.loading { color: transparent; background: linear-gradient(100deg, #eceff1 30%, #f6f7f8 50%, #eceff1 70%); animation: loading 1.2s ease-in-out infinite; }
Our animation line is setting the keyframe to
loading
, telling it to last for 1.2 seconds, setting the timing function toease-in-out
to make it smooth, and tell it to loop forever withinfinite
.If you notice though after saving that, it's still not doing anything. The reason for this is we're setting our gradient from one end of the DOM element to the other, so there's nowhere to move!
So let's try also setting a
background-size
on our.loading
class..loading { color: transparent; background: linear-gradient(100deg, #eceff1 30%, #f6f7f8 50%, #eceff1 70%); background-size: 400%; animation: loading 1.2s ease-in-out infinite; }
Now, since our background expands beyond our DOM element (you can't see that part), it has some space to animate with and we get our animation!
Follow along with the commit!
Part 2: Using our loading animation in a dynamic app
Now that we have our loading animation, let's put it into action with a basic example where we fake a loading state.
The trick with actually using this is typically we don't have the actual content available, so in most cases, we have to fake it.
To show you how we can do this, we're going to build a simple React app with Next.js.
Step 1: Creating an example React app with Next.js
Navigate to the directory you want to create your new project in and run:
yarn create next-app # or npm init next-app
It will prompt you with some options, particularly a name which will determine the directory the project is created in and the type of project. I'm using
my-css-loading-animation-dynamic
and the "Default Starter App".Once installed, navigate into your new directory and start up your development server:
cd [directory] yarn dev # or npm run dev
Next, let's replace the content in our
pages/index.js
file. I'm going to derive the content from the previous example, but we'll create it similar to how we might expect it to come from an API. First, let's add our content as an object above our return statement:const content = { header: `So, how 'bout them Knicks?`, intro: `What are their names? I'm Santa Claus! This opera's as lousy as it is brilliant! Your lyrics lack subtlety. You can't just have your characters announce how they feel. That makes me feel angry! Good news, everyone! I've taught the toaster to feel love!`, list: [ `Yes! In your face, Gandhi!`, `So I really am important? How I feel when I'm drunk is correct?`, `Who are those horrible orange men?` ] }
To display that content, inside
, let's replace the content with:
{ content.header }
{ content.intro }
- { content.list.map((item, i) => { return (
- { item } ) })}
And for the styles, you can copy and paste everything from our Part 1
main.css
file into thetags at the bottom of our index page. That will leave us with:
With that, we should be back to a similar point we finished at in Part 1 except we're not actively using any of the loading animations yet.
Follow along with the commit!
Step 2: Faking loading data from an API
The example we're working with is pretty simple. You'd probably see this coming pre-generated statically, but this helps us create a realistic demo that we can test our loading animation with.
To fake our loading state, we're going to use React's
useState
,useEffect
, and an old fashionedsetTimeout
to preload some "loading" content, and after thesetTimeout
finishes, update that content with our actual data. In the meantime, we'll know that we're in a loading state with a separate instance ofuseState
.First, we need to import our dependencies. At the top of our
pages/index.js
file, add:import { useState, useEffect } from 'react';
Above our
content
object, let's add some state:const [loadingState, updateLoadingState] = useState(true); const [contentState, updateContentState] = useState({})
And in our content, we can update the instances to use that state:
{ contentState.header }
{ contentState.intro }
- { contentState.list.map((item, i) => { return (
- { item } ) })}
Once you save and load that, you'll first notice we get an error because our
list
property doesn't exist on ourcontentState
, so we can first fix that:{ Array.isArray(contentState.list) && contentState.list.map((item, i) => { return (
- { item }
) })}And after that's ready, let's add our
setTimeout
inside of auseEffect
hook to simulate our data loading. Add this under ourcontent
object:useEffect(() => { setTimeout(() => { updateContentState(content); updateLoadingState(false) }, 2000); }, [])
Once you save and open up your browser, you'll notice that for 2 seconds you don't have any content and then it loads in, basically simulating loading that data asynchronously.
Follow along with the commit!
Step 3: Adding our loading animation
Now we can finally add our loading animation. So to do this, we're going to use our loading state we set up using
useState
and if the content is loading, add our.loading
class to our elements.Before we do that, instead of individually adding this class to each item in the DOM, it might make more sense to do so using CSS and adding the class to the parent, so let's do that first.
First, update the
.loading
class to target our elements:.loading h1, .loading p, .loading li { color: transparent; background: linear-gradient(100deg, #eceff1 30%, #f6f7f8 50%, #eceff1 70%); background-size: 400%; animation: loading 1.2s ease-in-out infinite; }
Then we can dynamically add our class to our
tag:
Note: if you use Sass, you can manage your loading styles by extending the
.loading
class in the instances you want to use it or create a placeholder and extend that!And if you refresh the page, you'll notice it's still just a blank page for 2 seconds!
The issue, is when we load our content, nothing exists inside of our tags that can that would allow the line-height of the elements to give it a height.
But we can fix that! Because our
.loading
class sets our text to transparent, we can simply add the wordLoading
for each piece of content:const [contentState, updateContentState] = useState({ header: 'Loading', intro: 'Loading', list: [ 'Loading', 'Loading', 'Loading' ] })
Note: We can't use an empty space here because that alone won't provide us with a height when rendered in the DOM.
And once you save and reload the page, our first 2 seconds will have a loading state that reflects our content!
Follow along with the commit!
Some additional thoughts
This technique can be used pretty broadly. Being a CSS class makes it nice and easy to add where every you want.
If you're not a fan of setting the
Loading
text for the loading state, another option is to set a fixed height. The only issue with that is it requires more maintenance for tweaking the CSS to match what the content loading in will look like.Крім того, це не буде ідеально. Найчастіше ви точно не будете знати, скільки копій у вас на сторінці. Мета полягає в імітації та натяканні на те, що вміст буде міститись і що він зараз завантажується.
Яка ваша улюблена анімація завантаження?
Повідомте мене в Twitter!
Приєднуйтесь до розмови!
Якщо ви чекаєте завантаження сторінки, це допоможе знати, що щось працює у фоновому режимі.
Тож ви повинні створити гарну анімацію завантаження для вашого додатка.
Ось чому @colbyfayock написав цей посібник, в якому показано, як створити цю анімацію із чистим CSS .//t.co/h8hGwqZ3sl
- freeCodeCamp.org (@freeCodeCamp) 24 травня 2020 р- ? Слідуйте за мною у Twitter
- ? Підписатися на мій Youtube
- Підпишіться на мою розсилку
) проти самого елемента списку (