Skip to content

Commit

Permalink
perf: optimize image lazyload
Browse files Browse the repository at this point in the history
  • Loading branch information
XPoet committed Nov 30, 2023
1 parent bd548c9 commit 595812b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
1 change: 1 addition & 0 deletions source/css/common/markdown.styl
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,7 @@

&[lazyload] {
margin 0.8rem auto 0.2rem
zoom 1 !important
}
}

Expand Down
19 changes: 11 additions & 8 deletions source/js/lazyload.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,20 @@ KEEP.initLazyLoad = () => {
function lazyload(imgs) {
now = Date.now()
needLoad = Array.from(imgs).some((i) => i.hasAttribute('lazyload'))

const h = window.innerHeight
const s = document.documentElement.scrollTop || document.body.scrollTop
const viewOffsetTop =
window.innerHeight + document.documentElement.scrollTop || document.body.scrollTop

imgs.forEach((img) => {
if (img.hasAttribute('lazyload') && !img.hasAttribute('loading')) {
if (h + s > img.offsetTop) {
const imgOffsetTop = window.scrollY + img.getBoundingClientRect().top

if (viewOffsetTop > imgOffsetTop) {
img.setAttribute('loading', true)
const loadImageTimeout = setTimeout(() => {
const temp = new Image()
const tempImg = new Image()
const src = img.getAttribute('data-src')
temp.src = src
temp.onload = () => {
tempImg.src = src
tempImg.onload = () => {
img.src = src
img.removeAttribute('lazyload')
img.removeAttribute('loading')
Expand All @@ -36,7 +37,9 @@ KEEP.initLazyLoad = () => {

window.onscroll = () => {
if (Date.now() - now > 50 && needLoad) {
lazyload(imgs)
if (imgs.length) {
lazyload(imgs)
}
}
}
}

0 comments on commit 595812b

Please sign in to comment.