Preloading Activity Indication via Pseudo-Elements

 — 3 Min Read

A common practice in software design is to display an infinite activity indicator while a server or client task is being performed with an unknown completion time. On the web, this often comes in the form of an animating image which obviously must itself be loaded.

There isn't much more jarring to a user than making a request and waiting, even for a fraction of a second, for part of the interface to catch up. This small lapse can be masked by preparing the loading indicator before the users' action requests it. There are several ways to achieve this with pseudo-elements. Here is one:

element {
    display: block;
    height: 200px;
}
element::after {
    content: '';
    display: none;
    position: absolute;
    top: 50%;
    left: 50%;
    background: url(images/loader.gif) 50% 50% no-repeat;
    width: 16px;
    height: 16px;
    margin: -8px 0 0 -8px;
}

This will render the pseudo-element invisibly, but ensure the browser has already pulled down images/loader.gif for when it's needed. When an event has been fired that requires the element to display as active, all we need is a class to pull the indicator into view instantly.

element.active::after {
    display: block;
}

Toggling the .active class via JavaScript will control the elements' activity indication. In most cases, the same effect can be achieved with background-position, visibility, opacity or other CSS definitions. It all depends on the context. Once again, this can be combined with the other methods outlined previously for an improved user experience: