Spruce up Link Tags with  Retrieved Favicons

Spruce up Link Tags with Retrieved Favicons


2 min read

So everybody loves links right? They take us to places we want to go.

Who wouldn't like them!

But they can be boring.๐Ÿฅฑ๐Ÿ’ค

Sure you can style them or manually get an image to show what the site is but why not get the websites own logo by using the Favicon from the link site and display it as well using the same url as the link? This would be pretty handy if we were creating links dynamically from a list eg [link1,link2,link3] ...

#####What is a Favicon anyway ? Alt Text The favicon is a small typically 16ร—16 pixel icon that serves as branding for websites. It is found in browser tab and within the browser address bar. TLDR Its a tiny site logo.

#####Our Example Alt Text We'll create a sample using a hardcoded value - 'dev.to/', but you can iterate over list of urls if you want. The only difference will be that you will be injecting the link.

We need to create two elements within the a tag - one for the image , the other for the link text. You can see the HTML needed below.

 <a  class="link-item" href="https://dev.to/" > 
       <span class="link-image">
             <img src=""  width="25" height="25" />
       <span class="link-text">

For the image source we can try two things: 1.Set the source as 'dev.to/favicon.ico' - the favicon can typically be found at the site root. 2.We can use Googleusercontent.com, which is a site that Google is using for a few things ,including storing website favicons visited by the search engine. Just use this as the source, set the domain value with the website url 's2.googleusercontent.com/s2/favicons?domain..

Either of these options are fine , but we could combine them using one as a fallback if the other fails using the javascript onerror event.

We can do that with the below:

<img src="https://dev.to/favicon.ico" 
     onerror="this.onerror=null; this.src='https://s2.googleusercontent.com/s2/favicons?domain=www.dev.to'" 
     alt="Dev.to" width="25" height="25"

The purpose of adding this.onerror=null; within the onerror event is to prevent an endless loop of errors if both fail.

That's it , its pretty simple !! Go congratulate yourself because your links look better already ๐ŸŽ‰๐ŸŽ‰

You can see a JSFiddle demo here

And if you're feeling generous you can buy me a coffee with the link below ( and yes its all for coffee, I drink a copius amount of it while writing โ˜• )

Buy Me A Coffee

Did you find this article valuable?

Support Jamie McManus by becoming a sponsor. Any amount is appreciated!