Skip to content

Commit

Permalink
Fix bug where cached image are revealed twice
Browse files Browse the repository at this point in the history
  • Loading branch information
ptrckvzn committed Jan 20, 2022
1 parent 3c3fe4d commit ffcdc93
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 12 deletions.
2 changes: 1 addition & 1 deletion resources/js/TwillImage.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class TwillImage {
image.wrapper = new Wrapper(image)
}
const intersectionObserver = createIntersectionObserver(() => {
image.wrapper.reveal()
!image.wrapper.revealed && image.wrapper.reveal()
image.wrapper.isCached && (image.wrapper.isLoaded = true)
})
image.wrapper.unobserve = intersectionObserver(image)
Expand Down
27 changes: 18 additions & 9 deletions resources/js/Wrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,33 @@ class Wrapper {
this.placeholder = el.querySelector('[data-placeholder-image]')
this.isLoading = hasNativeLazyLoadSupport()
this.isLoaded = false
this.onload = this.onload.bind(this)
this.load = this.load.bind(this)
this.reveal = this.reveal.bind(this)
this.cacheKey = JSON.stringify(this.main.src || this.main.dataset.src)
this.revealed = false

this.main.onload = this.onload
this.main.onload = (e) => this.load(e.currentTarget)

if (this.isLoading) {
this.reveal()
}

if (this.isLoading || this.main.complete) {
this.load(this.main)
}
}

set isLoaded(state) {
this._isLoaded = state
this.main.style.opacity = state ? 1 : 0

if (state) {
this.main.style.transition = 'opacity 500ms linear'
this.main.style.opacity = 1
} else {
this.main.style.transition = ''
this.main.style.opacity = 0
}

state && this.unobserve()
}

Expand Down Expand Up @@ -79,20 +92,16 @@ class Wrapper {
delete this.main.dataset.srcset
}

// if the main image is in the cache, onload function won't be called as an image was already loaded
if (this.main.complete) {
this.isLoaded = true
}
this.revealed = true
}

onload(e) {
load(target) {
if (this.isLoaded) {
return
}

storeImageloaded(this.cacheKey)

const target = e.currentTarget
const img = new Image()
img.src = target.currentSrc

Expand Down
2 changes: 0 additions & 2 deletions src/Services/ImageStyles.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,7 @@ public function main($loading = 'eager')
{
$style = array_merge(
[
'transition' => 'opacity 500ms ease 0s',
'transform' => 'translateZ(0px)',
'transition' => 'opacity 250ms linear',
'will-change' => 'opacity',
],
$this->baseStyle,
Expand Down

0 comments on commit ffcdc93

Please sign in to comment.