DEV Community

Cover image for Spruce up Link Tags with  Retrieved Favicons
Jamie Mc Manus
Jamie Mc Manus

Posted on • Updated on

Spruce up Link Tags with Retrieved Favicons

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 - 'https://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> 
       <span class="link-text">
               www.dev.to
       </span>
</a>
Enter fullscreen mode Exit fullscreen mode

For the image source we can try two things:
1.Set the source as 'https://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 'https://s2.googleusercontent.com/s2/favicons?domain=www.dev.to'

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"
/>
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)