如何提升页面打开的速度,我们不妨从图片下手,一方面我们要尽可能的使用更低像素的图片,另外一方面就是延迟加载图片,这样页面文字加载出来后,再显示图片,这样页面打开的速度就提升了。这两种实现方法相对简单,我们还有另外一种需求,如果我们不得不使用高像素的图片,而且页面打开时也要有图片,那就应该这样做。
javascript代码:
<script type="text/javascript">
//Written by Paul Seal 2015. Shared on www.codeshare.co.uk in October 2015
//You are free to use, modify and distribute this however you want.
//-----------------------------------------------------------------
var lazyImages = {
init: function () {
revealNextImage();
function replaceThisLazyImage(element, bgImage) {
if (element != null && element != undefined) {
var imagePath = $(element).attr("data-image-path");
var image = new Image();
$(image)
.load(function () {
if(bgImage) {
$(element).css("background-image", "url(" + imagePath + ")");
}
else {
$(element).attr("src", imagePath);
}
$(element).removeClass('lazyimage');
revealNextImage();
})
.attr('src', imagePath)
}
}
function revealNextImage() {
replaceThisLazyImage($('.lazyimage:not(img):first')[0], true);
replaceThisLazyImage($('img.lazyimage:first')[0], false);
}
}
}; $(window).load(lazyImages.init);
</script>
您可以使用它于背景图像和前景图像。
背景
<header class="lazyimage" style="background-image: url('/images/smallerimage.jpg');" data-image-path="/images/largerimage.jpg">
</header>
前景
<img class="lazyimage" height="185" src="/images/smallerimage.jpg" data-image-path="/images/largerimage.jpg">
你只需要添加一个
class=“lazyimage”
和data-image-path
属性
(更高质量图像的路径)。然后您可以在前景图像中的src,或者在背景图像风格中输入低质量的图像的路径。