渐进式图片加载是一种优化图片加载的策略,主要用于提升网页加载速度和用户体验。这种策略的核心思想是,先加载图片的模糊版本或低分辨率版本,然后再逐渐加载高清版本。这样,用户可以在图片完全加载之前看到图片的大致内容,从而提高页面的响应速度。
完整组件代码:
<template>
<view
:class="{ 'gradual-image': true, 'success-image': isSuccess }"
:style="{ width: width + 'rpx', height: height + 'rpx', ...classStyle }"
>
<!-- 缩略图 -->
<image
v-if="placeholderImage"
class="image placeholder-image"
:style="`transition: ${duration / 1000}s`"
:mode="mode"
:src="placeholderImage"
/>
<view v-else class="none-image">正在加载...</view>
<!-- 原图 -->
<image
class="image original-image"
:style="`transition: ${duration / 1000}s`"
:mode="mode"
:src="originalImage"
@load="handleLoad"
/>
</view>
</template>
<script>
export default {
props: {
// 原图
originalImage: {
type: String,
default: '',
required: true
},
// 占位图
placeholderImage: {
type: String,
default: ''
},
// 图片模式
mode: {
type: String,
default: 'scaleToFill'
},
// 宽度,单位:rpx
width: {
type: [String, Number],
default: 200
},
// 高度,单位:rpx
height: {
type: [String, Number],
default: 200
},
// 过渡时间,单位:ms
duration: {
type: [String, Number],
default: 500
},
// 样式
classStyle: {
type: Object,
default: () => ({})
}
},
data() {
return {
isSuccess: false // 是否加载完原图
}
},
methods: {
// 原图加载完成
handleLoad(e) {
this.isSuccess = true
}
}
}
</script>
<style lang="scss" scoped>
.gradual-image {
position: relative;
.image {
width: 100%;
height: 100%;
display: block;
}
.none-image {
width: 100%;
height: 100%;
background-color: #f6f6f6;
display: flex;
align-items: center;
justify-content: center;
color: #999999;
font-size: 24rpx;
}
.original-image {
position: absolute;
top: 0;
left: 0;
opacity: 0;
filter: blur(10rpx);
}
}
.success-image {
.original-image {
opacity: 1;
filter: blur(0);
}
}
</style>
组件使用如下:
<template>
<bcode-gradualimage
originalImage="https://cdn.zxmcode.top/siege_cat/DSCF2854.jpg"
placeholderImage="https://cdn.zxmcode.top/siege_cat/DSCF2854.jpg/thumbnail"
mode="aspectFill"
:classStyle="classStyle"
></bcode-gradualimage>
</template>
<script setup lang="ts">
const classStyle = {
width: '750rpx',
height: '100vh'
}
</script>
<style lang="scss" scoped></style>
蓝码前端小程序
蓝码前端公众号