Gravatar是gravatar推出的一项服务,意为“全球通用头像”。如果在Gravatar的服务器上放置了你自己的头像,那么在任何支持Gravatar的blog或者留言本上留言时,只要提供你与这个头像关联的email地址,就能够显示出你的Gravatar头像来。
Gravatar头像使用起来确实很方便,但是在网站评论多了以后面临的问题就是一大片头像的加载。所以可以考虑延迟加载头像,优化下网页加载速度,提升用户体验。
大家都知道有个lazyload的东西 可以让你的页面图片在滚动到位置后才去显示 通过这样来实现加速打开页面的效果。首先找到你的WP下面的?wp-includes/pluggable.php文件,找到get_avatar函数 拉到最下面找到(以下修改只会影响到你调用get_avatar显示的头像,需要其它图片也这么显示的话 请自己修改)。
$avatar = "<img alt='{$safe_alt}' src='https://www.xhsay.com/{$out}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' /&gt;";
修改为
if (!is_admin()) { $avatar = "<img alt='{$safe_alt}' src='https://www.xhsay.com/avatar/default.jpg' class='avatar avatar-{$size} photo lazyload' lazyload='https://www.xhsay.com/{$out}' height='{$size}' width='{$size}' />"; }else{ $avatar = "<img alt='{$safe_alt}' src='https://www.xhsay.com/{$out}' class='avatar avatar-{$size} photo lazyload' height='{$size}' width='{$size}' />"; }
注意修改图片地址为你的默认头像地址,再加载上JS文件就可以在窗口滚动到图片位置才显示图片。
jQuery(document).ready(function() { var c = $("img.lazyload"), d = function(a) { var b = $(window).height() + $(document).scrollTop(); c.each(function() { $(this).offset().top < b && ($(this).trigger("appear"), c = c.not(this)); }), 0 == c.length && $(window).unbind("scroll", d); }; c.each(function() { $(this).one("appear", function() { $(this).attr("src", $(this).attr("lazyload")); }); }), $(window).bind("scroll", d), d(); });
原理很简单,就是默认输出的头像全部都是你指定的默认头像。然后通过JS来 把lazyload的值赋给src。然后窗口滚动到头像位置的时候 再用appear去显示它。
HOOK方法:上面的方法在升级wordpress程序后,修改的文件会被覆盖掉。可以自己在主题的funtions.php上写个Hook代码来解决。
将以下代码加入主题funtions.php中:
function mytheme_get_avatar($avatar) { if (!is_admin()){ $avatar = str_replace(array("src"),"src='https://www.xhsay.com/avatar/default.jpg' lazyload",$avatar); $avatar = str_replace(array("avatar-"),"lazyload avatar-",$avatar); } return $avatar; } add_filter( 'get_avatar', 'mytheme_get_avatar', 10, 3 );
- 首先你的主题使用的是 get_avatar函数来调用头像的,如果不是 请把最后一行的get_avatar替换成你自己的调用头像函数
- 如果你已经使用了hook的方法来缓存头像到本地 那你可以直接把 两句str_replace代码加到你的缓存头像函数最后的 return $avaatar之前就可以了