#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →

Add Loading Animations Using Lottie and JSON Files

A Lottie animation is a JSON file that describes vector shapes and keyframes. A small player library (lottie-web) reads that file and draws the animation in the browser as SVG or canvas. This guide shows how to add one as a loading indicator, wire it to a real fetch() call and keep it accessible and light.

Add Loading Animations Using Lottie and JSON Files

What Lottie is

Lottie is an open-source animation format and player that Airbnb released in 2017. A designer builds the animation in Adobe After Effects and exports it with the Bodymovin plugin. The export is a .json file. Players exist for the web (lottie-web), Android, iOS and React Native, so the same file can run on all of them.

For a loading indicator this has three practical benefits:

  • It scales. Shapes are vectors, so the spinner stays sharp on any screen density.
  • It is small when built well. A simple spinner made only of shapes is often a few kilobytes of JSON, smaller than an animated GIF of the same size.
  • It is controllable. You can play, pause, change speed or jump to a frame from JavaScript.

The trade-off: you add a player script to the page, and complex animations with many layers can cost CPU time. For a plain spinning circle, CSS alone is lighter. Use Lottie when you want a branded or illustrated loader that would be hard to build in CSS.

What is inside the JSON file

You rarely edit the file by hand, but knowing the top-level keys helps when something looks wrong:

KeyMeaning
vBodymovin version that exported the file
frFrame rate (for example 30 or 60)
ip / opIn point and out point: the first and last frame
w / hWidth and height of the composition in pixels
layersThe layers; each has a type ty (4 = shape, 0 = precomp, 1 = solid, 2 = image, 3 = null, 5 = text)
assetsPrecompositions and any embedded images

Duration in seconds is (op - ip) / fr. A file with "ip":0,"op":60,"fr":30 plays for 2 seconds per loop.

Colours sit inside fill and stroke items as arrays of values from 0 to 1, for example "c":{"a":0,"k":[0.18,0.44,0.84,1]}. That is RGB(46, 112, 214) at full opacity. Changing those numbers is the quickest way to match a loader to your brand colours without opening After Effects.

Step 1: get an animation file

You have two options:

  1. Ask a designer to export from After Effects with Bodymovin. Ask for shape layers only, no embedded raster images, and a short loop (1–2 seconds).
  2. Download a free animation from a library such as LottieFiles. Check the licence for each file before you use it on a commercial site.

Save it in your project, for example /animations/loader.json. Open it once in a text editor: if you see long "p":"data:image/png;base64,..." strings, the file contains bitmap images and will be much heavier than it needs to be.

Step 2: load it with lottie-web

Add the player from a CDN or install it with npm install lottie-web. The version number below is an example; use the current release from the project's page.

<div id="loader" role="status" aria-live="polite">
  <div id="loader-anim" style="width:120px;height:120px" aria-hidden="true"></div>
  <span class="sr-only">Loading…</span>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/lottie-web/5.12.2/lottie.min.js"></script>
<script>
  const anim = lottie.loadAnimation({
    container: document.getElementById('loader-anim'),
    renderer: 'svg',      // 'svg', 'canvas' or 'html'
    loop: true,
    autoplay: true,
    path: '/animations/loader.json'   // or animationData: importedJsonObject
  });
</script>

Two common errors at this stage:

  • Nothing appears when you open the HTML file directly. The path option downloads the JSON with a network request, and browsers block that for file:// pages. Run a local server (for example npx serve or python -m http.server).
  • The container has no size. The player fills its container. A div with zero height shows nothing, so give it a width and height.

Step 3: show the loader only while work is happening

A loading animation is useful only when it is tied to a real wait. The pattern below shows the loader during a fetch(), hides it when the request ends (success or failure) and frees the player's memory.

<div id="content" hidden></div>

<script>
async function loadCourses() {
  const loader  = document.getElementById('loader');
  const content = document.getElementById('content');

  // Show the loader only if the request takes longer than 300 ms,
  // so fast responses don't flash an animation for a split second.
  loader.hidden = true;
  const showTimer = setTimeout(() => { loader.hidden = false; }, 300);

  try {
    const res = await fetch('/api/courses');
    if (!res.ok) throw new Error('HTTP ' + res.status);
    const courses = await res.json();
    content.textContent = courses.length + ' courses loaded';
  } catch (err) {
    content.textContent = 'Could not load courses. Please try again.';
  } finally {
    clearTimeout(showTimer);
    anim.destroy();        // removes the SVG and stops the animation loop
    loader.remove();
    content.hidden = false;
  }
}
loadCourses();
</script>

The 300 ms delay is a design choice, not a rule. The point is to avoid a loader that blinks on and off when the server answers quickly.

Step 4: control playback

The object returned by loadAnimation() has methods you will use often:

Method / eventWhat it does
anim.play(), anim.pause(), anim.stop()Start, pause, or stop and rewind to the first frame
anim.setSpeed(1.5)Play 1.5 times faster
anim.goToAndStop(30, true)Jump to frame 30 and hold it (true means the value is a frame, not milliseconds)
anim.playSegments([0, 45], true)Play only frames 0–45
anim.destroy()Remove the animation and release memory
'complete', 'loopComplete', 'DOMLoaded'Events you can listen to with anim.addEventListener()

Segments are handy for a loader that has an intro, a loop and a "done" tick. Play the loop segment while waiting, then play the tick segment once the data arrives and remove the loader on 'complete'.

Step 5: respect reduced motion

Some users turn on "reduce motion" in their operating system because animation makes them dizzy or distracts them. Check that setting and show a still frame instead:

const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

const anim = lottie.loadAnimation({
  container: document.getElementById('loader-anim'),
  renderer: 'svg',
  loop: !reduceMotion,
  autoplay: !reduceMotion,
  path: '/animations/loader.json'
});

if (reduceMotion) {
  anim.addEventListener('DOMLoaded', () => anim.goToAndStop(0, true));
}

Keep the visible or screen-reader text ("Loading…") in either case. The animation is decoration; the text is what tells assistive technology that something is happening. That is why the animation container has aria-hidden="true" and the wrapper has role="status".

Using Lottie in React

In a React app, a wrapper package such as lottie-react saves you from managing the player yourself. It creates the animation on mount and destroys it on unmount.

import Lottie from 'lottie-react';
import loader from './loader.json';

export default function Loader() {
  return (
    <div role="status" aria-live="polite">
      <div aria-hidden="true">
        <Lottie animationData={loader} loop style={{ width: 120, height: 120 }} />
      </div>
      <span className="sr-only">Loading…</span>
    </div>
  );
}

Render <Loader /> while your data hook reports a loading state. Importing the JSON puts it inside your JavaScript bundle; for large files, load it with path or a dynamic import() instead so it does not slow the first page load. If you also need UI motion beyond loaders, see this guide to animations in React with Framer Motion.

Keeping it fast

  • Choose the renderer. svg gives the sharpest result and is the usual default. canvas can be faster when many animations run at once, because it does not create DOM nodes for every shape.
  • Use the light build if you can. lottie-web ships a smaller lottie_light build that supports only the SVG renderer and no After Effects expressions. Test your file with it; if it plays correctly, use it.
  • Load the player without blocking. Add defer to the script tag (see async vs defer in JavaScript) so it does not hold up HTML parsing.
  • Compress the JSON. Serve it with gzip or Brotli. JSON compresses well. The .lottie format (a zipped package) is another option, but it needs the dotLottie player instead of plain lottie-web.
  • Destroy what you no longer need. A looping animation that is merely hidden with CSS can keep running. Call destroy() or at least pause().

Lottie or CSS?

If your loader is a spinning ring, three bouncing dots or a progress bar, CSS keyframes do the job with no extra script; this tutorial on animated progress bars in CSS shows the approach. Choose Lottie when the animation comes from a designer, has illustrated shapes or many moving parts, or must look identical in your web and mobile apps. For scroll-based effects rather than loaders, libraries such as AOS are a better fit; see scroll reveal animations with AOS.

Checklist before you ship

  • The loader appears only during a real wait, and disappears on both success and error.
  • The JSON file has no embedded bitmaps and is served compressed.
  • Reduced-motion users see a still frame plus "Loading…" text.
  • The container has a fixed size, so the page does not jump when the animation loads.
  • destroy() is called when the loader is removed.

Reference: the lottie-web README and documentation on GitHub (airbnb/lottie-web); MDN pages for fetch() and prefers-reduced-motion.

Placed Students

Our Clients

Partners

...