Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(H5): image 组件支持lazy-load属性 #4141

Open
wants to merge 2 commits into
base: next
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 30 additions & 2 deletions packages/uni-components/src/vue/image/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,32 @@ function useImageLoader(
state.origHeight = height
state.imgSrc = imgSrc
}
const loadImage = (src: string) => {

const observer = ref<IntersectionObserver>()
const cleanupObserver = () => {
if (observer.value) {
observer.value?.disconnect()
observer.value = undefined
}
}
const lazyLoadImage = (src: string) => {
resetImage()
setState()
if (!observer.value) {
observer.value = new IntersectionObserver(([{ isIntersecting }]) => {
if (isIntersecting) {
_loadImage(src)
cleanupObserver()
}
})
observer.value.observe(state.rootEl!)
}
}

const loadImage = (src: string) =>
props.lazyLoad ? lazyLoadImage(src) : _loadImage(src)

const _loadImage = (src: string) => {
if (!src) {
resetImage()
setState()
Expand Down Expand Up @@ -192,7 +217,10 @@ function useImageLoader(
}
)
onMounted(() => loadImage(state.src))
onBeforeUnmount(() => resetImage())
onBeforeUnmount(() => {
cleanupObserver()
resetImage()
})
}

const isChrome = __NODE_JS__ ? false : navigator.vendor === 'Google Inc.'
Expand Down