Preloading images in plain HTML

Preloading images in plain HTML

Recently I needed to preload images for my upcoming web game:, but me being me, I didn't feel like building a complex solution using JS. A bit of good ol' Googling later, I discovered the "prefetch" method in plain HTML.

Preloading images prevents those awkward flashes where the browser doesn't know the dimensions of the image you're loading and moves your layout around. In dynamic applications and games, this can be a small but undesirable UI issue.

Prefetch is dead simple to use too.

Inside your HTML file(s), simply add <link> tags with the appropriate rel attributes within your <head> section:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="theme-color" content="#000000" />

    <!-- Secret sauce incoming: -->
    <link rel="prefetch" href="/ui/Logo.png" />

  <!-- ... -->

Now, wherever you use the image /ui/Logo.png (be it in your HTML, or dynamically via JS) will load it instantly, without any broken UI while the image loads... Because it's already loaded in the browser's memory.

For me, this was a perfect drop-in solution. I hope it proves helpful to you as well!

As always, keep on creating! ❤️