リンクに自動でファビコンを付ける

Ads

Result

jQuery

//リンクをセレクタに指定
$('a[href^="http://"]').filter(function() {
    //URLのホスト名を取得する
    return this.hostname && this.hostname !== location.hostname;
}).each(function(){
    //正規表現でファビコンを認識、取得
    var l = $(this);
    var fu = l.attr('href').replace(/^(http:\/\/[^\/]+).*$/, '$1') + '/favicon.ico';
    var fi = $('<img src="favicon.png" alt="favicon" />')['prependTo'](l);
    var e = new Image();
    e.src = fu;
    //ファビコンがあったら表示する
    if (e.complete) fi.attr('src', fu);
    else e.onload = function(){
        fi.attr('src', fu);
    };
});

css

img{width:15px;height:15px;}
a{text-decoration:none;color:green;margin-bottom:5px;display:inline-block;}

html

<a href="/">kachibito</a><br />
<a href="http://www.facebook.com/">facebook</a><br />
<a href="http://twitter.com/">twitter</a><br />
<a href="http://www.youtube.com/">youtube</a><br />
<a href="http://www.flickr.com/">flickr</a><br />
<a href="http://b.hatena.ne.jp/">hatena</a><br />

via

Add favicon to external links with jQuery – Snipplr

Warning: include(/home/youhei0828/kachibito.net/public_html/wp-content/themes/cocoon-master/my-php/jquery-other-snippets.php): Failed to open stream: No such file or directory in /home/youhei0828/kachibito.net/public_html/wp-content/themes/kachibito7_with_cocoon_child/functions-module/shortcode/add-post-myphp.php on line 7

Warning: include(): Failed opening '/home/youhei0828/kachibito.net/public_html/wp-content/themes/cocoon-master/my-php/jquery-other-snippets.php' for inclusion (include_path='.:/opt/php-8.1.29/data/pear') in /home/youhei0828/kachibito.net/public_html/wp-content/themes/kachibito7_with_cocoon_child/functions-module/shortcode/add-post-myphp.php on line 7