Using animated GIFs (or not)

The GIF image format is pretty old, but still very popular. Generally, it is recommended to convert GIF to PNG8, because it results in a 21% smaller file size.

But PNG images do not support animations. So that is probably the main reason that GIFs are still in use. Especially on sites or in apps that have a timeline, like Twitter, Facebook, Slack or WhatsApp. This post was actually triggered by a discussion on the Web Performance Slack channel (get an invite).

If you still want to use GIF, you can optimise images with Gifsicle. It is already included in tools like ImageOptim and imagemin-app.


gifsicle -O3 -o output.gif input.gif 

As a side effect of the popularity of animated GIFs, news sites like the Washington Post are using them. Their article on a robot snake to charge a Tesla includes a 4.3 MB GIF. They could have used a video instead. Converting the image to a MP4 with FFmpeg results in a file size of 143 KB. That is a difference of more than 3000%.


ffmpeg -i image.gif -c:v libx264 -an -movflags faststart -pix_fmt yuv420p -s 544x292 video.mp4

The dimensions of this video needed to be changed, because the width and height must be divisible by 2 for the H.264 video codec.

In HTML5 you can embed the video with autoplay:


<video controls autoplay muted loop playsinline>
  <source src="video.mp4" type="video/mp4">
  <img src="fallback.jpg" alt="Video Screenshot">
</video>

A fallback video format like WebM or OGG Theora is not needed anymore, because all browsers, that support the HTML5 video element, also support MP4. Old browsers will get the fallback image. You also can use JavaScript to test for H.264 support.


function supportsH264() {
  var support = false;

  try {
    support = !!document.createElement("video").canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, "");
  } catch (ignore) {}

  return support;
}

Autoplay is not available on all mobile browsers, but that is probably a good thing. You could use canvid.js, if you insist on having autoplay on iOS. It will probably also work on Android, but I haven’t tested it.

The WebP image format also supports animations. The WebP library from Google includes gif2webp to convert GIFs. The result for the robot snake image is a 3.3 MB WebP file, so not a really big win compared to MP4.


gif2webp input.gif -o output.webp

So, go ahead and save some bandwidth.

[update]
Another solution could be to use BPG: Why BPG will replace GIFs and not only.

[update]
Added “playsinline” attribute.

Back to top