jQuery Add Site Favicon to External Links

By Sam Deering

It may be the case that you want to make all external links on your page visible to the user. It might be that you want to use the the favicon.ico of the external site that your linking to (if it is available).

Here is how you do it!

     return this.hostname && this.hostname !== location.hostname;
}).each(function() {
    var link = jQuery(this);
	//assuming it's in the root directory
    var faviconURL =
      link.attr('href').replace(/^(http://[^/]+).*$/, '$1')+'/favicon.ico';
    var faviconIMG = jQuery('')['appendTo'](link);
    var extImg = new Image();
    extImg.src = faviconURL;
    if (extImg.complete)
      faviconIMG.attr('src', faviconURL);
      extImg.onload = function() { faviconIMG.attr('src', faviconURL); };

No Reader comments

Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.