如果网站图片很多的话,一张1M ,100个请求就是并发带宽100M,导致网站加载慢,这个时候加上图片延迟加载,能有效的提升网站加载速度。
要实现图片延迟加载必须要把真实图片地址写在 data-original 属性。若src和data-original 属性data-original相同,只是一个特效,并不能实现图片延迟加载。
实现图片延迟加载的标签
1# Typecho标签
2<img src="img/loading.png">
3
4# lazyload标签
5<img class="lazyload" src="img/loading.png" data-original="example.jpg">
这里看到typecho的图片输出标签,缺少date-original标签,需要手动补全代码。本来想着使用JS实现,想着太麻烦。好奇的在全局搜索代码的时候,发现了相关的输出函数。
gravatar头像延迟加载
在var/Widget/Abstract/Comments.php 大概是395-408行
1 /**
2 * 调用gravatar输出用户头像
3 *
4 * @access public
5 * @param integer $size 头像尺寸
6 * @param string $default 默认输出头像
7 * @return void
8 */
9 public function gravatar($size = 32, $default = NULL)
10 {
11 if ($this->options->commentsAvatar && 'comment' == $this->type) {
12 $rating = $this->options->commentsAvatarRating;
13
14 $this->pluginHandle(__CLASS__)->trigger($plugged)->gravatar($size, $rating, $default, $this);
15 if (!$plugged) {
16 $url = Typecho_Common::gravatarUrl($this->mail, $size, $rating, $default, $this->request->isSecure());
17 echo '<img class="avatar" src="' . $url . '" alt="' .
18 $this->author . '" width="' . $size . '" height="' . $size . '" />';
19 }
20 }
21 }
这里看到这段代码
1<img class="avatar" src="' . $url . '" alt="' .$this->author . '" width="' . $size . '" height="' . $size . '" />
替换成
1<img class="avatar" src="占位图地址" data-src="' . $url . '" alt="' .$this->author . '" width="' . $size . '" height="' . $size . '" />
img图片输出
在var/HyperDown.php 大概在484-496行
1 $text = preg_replace_callback(
2 "/!\[((?:[^\]]|\\\\\]|\\\\\[)*?)\]\[((?:[^\]]|\\\\\]|\\\\\[)+?)\]/",
3 function ($matches) use ($self) {
4 $escaped = htmlspecialchars($self->escapeBracket($matches[1]));
5
6 $result = isset( $self->_definitions[$matches[2]] ) ?
7 "<img src=\"{$self->_definitions[$matches[2]]}\" alt=\"{$escaped}\" title=\"{$escaped}\">"
8 : $escaped;
9
10 return $self->makeHolder($result);
11 },
12 $text
13 );
找到
1<img src=\"{$self->_definitions[$matches[2]]}\" alt=\"{$escaped}\" title=\"{$escaped}\">
替换成
1<img class="lazyload" src="占位图地址" data-src=\"{$self->_definitions[$matches[2]]}\" alt=\"{$escaped}\" title=\"{$escaped}\">
在footer.php 标签前,加入
引入jquery.js和jquery.lazyload.js,并初始化lazyload的图片显示样式
1// 引入lazyload
2<script src="https://cdn.bootcss.com/jquery_lazyload/1.9.7/jquery.lazyload.min.js"></script>
3<script>
4 //js出始化lazyload
5 $(function() {$("img.lazyload").lazyload({effect: "fadeIn", threshold: 200});});
6 $(function() {$("img.avatar").lazyload({effect: "fadeIn", threshold: 200});});
7</script>
如果有pjax设置回调