SVG and CSS for simple loading spinners

A sampling of some loading icons gone wrong, in a single gif:

We all need loading spinners/icons from time to time. For years, an animated gif was the quick and easy way to go. But these days we've got options like spin.js and sites like cssload.net. The flip side is that all that stuff is heavy for what it accomplishes. In many cases, the result can end up being a hideous distraction (see above). But mainly it's a heavy solution to a simple problem. Do you want a library for a loading icon? A double-digit number of DOM elements and 100+ lines of CSS?

What's the alternative? As the post title implies, a little SVG and some CSS goes a long way.

The other day I came across a great example of a lightweight loading icon. After digging into how that one works (hint: add a loading class to <body>), my interest was piqued.

I started experimenting with svg's animate tag but chrome warned me not to do that because that stuff is going away. So I switched to CSS animation.

The simplest example I came up with rotates a line. That's probably not the best because I doubt most would recognize it as a loading icon. In a recent project I worked on there was an existing (d3-based) spinner that showed a rotating chunk of a circle. I liked that (but not the d3 dependency) so I made one using SVG and CSS. The svg required is a bit more complicated but it's nothing special. I also did another one that draws a circle.

This technique isn't exactly copy and paste, and takes a tiny bit more effort, but in the end you're getting a loading spinner for a few hundred bytes (depending on the complexity of your svg). And you're avoiding additional cruft, extra javascript and one or more http requests for something that should be simple and straightforward.