Passa al contingut principal

Favicons Next To External Links

Favicons Next To External Links:
I've had this JSFiddle from CSS Wizardry open for like 2 weeks in my browser. I kept thinking about it, because before that I got an email from someone asking about essentially the same thing and it stuck in my head. They were wanting to insert a favicon next to links and use only CSS to do it. Unfortunately I haven't found a way to do exactly that, but using some jQuery we can do it pretty easily.

The "I Wish" CSS Only Technique

What would be nice is if you had simple semantic HTML like this:
<a href="http://github.com">GitHub</a>
And then you could access everything you needed to insert a background image of the favicon using a service like getFavicon.
/* Fair warning, this doesn't work */

a[href^="http"]:before {
  content: url(http://g.etfv.co/ + attr(href) + );
}
Maybe the syntax wouldn't be exactly like that, but something like it. The point is, you can't mix up the url() syntax into parts like that in CSS.

Google's Favicon Service

Google has it's own favicon service you can use. For example:
http://www.google.com/s2/u/0/favicons?domain=css-tricks.com
The trick is you need just the host name and TLD and nothing else. I searched around and found a simple regex for getting that from any URL. We'll need that because links aren't always (or even usually) the root of sites.
function getDomain(url) {
   return url.match(/:\/\/(.[^/]+)/)[1];
}
Using these things, and jQuery, we'll find all links and apply the favicon as a background image. The external link checking is pretty rudimentary, but there are more robust methods here if need be.
$("a[href^='http']").each(function() {
    $(this).css({
        background: "url(http://www.google.com/s2/u/0/favicons?domain=" + getDomain(this.href) +
        ") left center no-repeat",
        "padding-left": "20px"
    });
});
Then @travis reminded me that you can just use this.hostname instead of the fancy regex. So:
/* Nothing else needed */
$("a[href^='http']").each(function() {
    $(this).css({
        background: "url(http://www.google.com/s2/u/0/favicons?domain=" + this.hostname +
        ") left center no-repeat",
        "padding-left": "20px"
    });
});
I'm not sure what the browser support is for hostname, whether it's just as good as href or less so, not sure.

getFavicon Method

@seanodotcom showed me another similar service galled getFavicon. It's hosted by Google AppEngine, but it's not Google's own service. I did find it a bit slower. But the advantage being that you don't need to deal with host names at all, you just give them the full URL.
So then it becomes:
$("a[href^='http']").each(function() {
    $(this).css({
        background: "url(http://g.etfv.co/" + this.href + ") left center no-repeat",
        "padding-left": "20px"
    });
});​
View Demo

Performance?

As I'm sure you know, the number of HTTP requests a page makes is a huge deal in performance. Each little image in these techniques are one page request each.
@yuritkanchenko pointed out to me a cool favicon service that can automatically sprite the favicons for you so you can keep it to one request.
For instance:
http://favicon.yandex.net/favicon/google.com/yandex.ru/css-tricks.com


I'm afraid I didn't go the extra mile here and write the JavaScript needed to find all links, concatenate the domains, make the request, and then apply the images as a sprite, but I'm sure you could whip that up pretty quick if you really needed it.
Favicons Next To External Links is a post from CSS-Tricks

Comentaris

Entrades populars d'aquest blog

10 alternativas a Cuevana para ver películas online

10 alternativas a Cuevana para ver películas online : Durante este último tiempo, en Cuevana se sucedieron varios “problemas” por los cuales hubo que ajustar algunas cosas antes de tiempo (como el rediseño del sitio), que dejaron a algunos usuarios ciertos problemas para acceder a las películas o series del portal. Pero realmente esto es algo que no incumbe a los usuarios y, como sabemos, existen muchas otras alternativas a Cuevana dando vueltas por Internet, que intentaremos presentar aquí mismo. Los sitios que repasaremos funcionan del mismo modo que Cuevana, mediante la instalación de un plugin que permite visualizar los videos de Megaupload o WUShare, entre otros servicios, en una calidad de imágen realmente excelente. Tal como sucede con el más popular servicio, todos ellos tienen publicidad que en algunos casos resulta insoportable, pero como dice Federico en DotPod “a caballo regalado no se le miran los dientes”. Alternativas a Cuevana 1. Moviezet Posiblemente el mejor clon d...

Learn Composition from the Photography of Henri Cartier-Bresson

“Do you see it?” This question is a photographic mantra. Myron Barnstone , my mentor, repeats this question every day with the hopes that we do “see it.” This obvious question reminds me that even though I have seen Cartier-Bresson’s prints and read his books, there are major parts of his work which remain hidden from public view. Beneath the surface of perfectly timed snap shots is a design sensibility that is rarely challenged by contemporary photographers. Henri Cartier-Bresson. © Martine Franck Words To Know 1:1.5 Ratio: The 35mm negative measures 36mm x 24mm. Mathematically it can be reduced to a 3:2 ratio. Reduced even further it will be referred to as the 1:1.5 Ratio or the 1.5 Rectangle. Eyes: The frame of an image is created by two vertical lines and two horizontal lines. The intersection of these lines is called an eye. The four corners of a negative can be called the “eyes.” This is extremely important because the diagonals connecting these lines will form the breakdown ...

Más de 50 de las mejores herramientas online para profesores

No es una exageración afirmar que hay ciento de aplicaciones educativas por ahí por la red, para todos los gustos y de todos los colores, por lo que es difícil tratar de recogerlas todas en un listado. Sin embargo, algunas destacan más que otras por su innovación y por su capacidad para conseguir adeptos, y esas son las que protagonizan la presente recopilación. Son 50 interesantes herramientas online basadas en las recopilaciones de EduArea , las muchas ya tratadas en Wwwhat’s new y las destacadas por la experiencia. 1. Dropbox : Un disco duro virtual con varios GB gratuitos y al que se accede desde casi cualquier dispositivo. Sin embargo, es muchísimo más que eso, de hecho ya comentamos 20 razones . 2. Google Drive : La evolución de Google Docs que suma a sus múltiples herramientas de creación de documentos, un considerable espacio virtual gratuito. 3. CloudMagic : Una extensión y una app multidispositivo para buscar información simultáneamente en Gmail, Twitter, Facebook, Evernote ...