Explain Codes LogoExplain Codes Logo

Add Favicon to Website

html
responsive-design
performance
best-practices
Alex KataevbyAlex Kataev·Aug 30, 2024
TLDR

To set up a favicon swiftly, add a <link> tag in your HTML's <head>:

<link rel="icon" href="/favicon.ico">

This simple piece of code is directing browsers towards "/favicon.ico" to function as your website's icon. Using .ico format is efficient as it can bundle multiple sizes like 16x16, 32x32, and 48x48 pixels together.

Creating multi-size favicons

Favicons should adapt to different device sizes. The design standards of responsiveness apply to favicons as well:

<!-- Standard favicon, comes in 16x16, 32x32, 48x48 sizes --> <link rel="icon" href="/favicon.ico" sizes="16x16 32x32 48x48" type="image/x-icon"> <!-- Because iPhones deserve special treatment --> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"> <!-- You gotta take care of Microsoft users too --> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/mstile-144x144.png">

Storing favicons correctly

Normally, favicons are stored at the root of your domain. But if you're feeling adventurous, you can place it in a subdirectory.

<!-- if you're storing it in the images subdirectory, for instance --> <link rel="icon" href="images/favicon.ico">

Whatever you choose, remember to update the href attribute!

Adapting to file format compatibility

Even though .ico is the old reliable, modern browsers can handle more than just that. They now roll with other formats like .png and .svg.

<!-- Older browsers, meet favicon.ico --> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"> <!-- PNG/SVG favicons, meet newer browsers --> <link rel="icon" href="/favicon.png" type="image/png"> <link rel="icon" href="/favicon.svg" type="image/svg+xml">

Jazz it up with a dynamic favicon

Favicons can also have a life of their own. By changing your favicon based on user interaction or time of day, you make your website more engaging:

let icon = document.querySelector('link[rel="icon"]'); // Do users visit in the morning? Give 'em a coffee cup icon! if (new Date().getHours() < 12) { icon.href = '/morning-favicon.ico'; } else { // It's beer-o'-clock somewhere! icon.href = '/evening-favicon.ico'; }

Avoiding common pitfalls

Browser cache issues can make your favicon updates invisible. Also, not all favicon generators produce quality icons. Sometimes, you hit the performance jackpot with unnecessary files:

<!-- sometimes, you gotta force the issue with caching --> <link rel="icon" href="/favicon.ico?v=2"> <!-- and what might be the performance cost of pixels? --> <link rel="icon" href="/massive-unoptimized-favicon.png">