46 lines
1.0 kB
1
import { Component } from 'preact'
2
3
export class Image extends Component {
4
state = {
5
loaded: false,
6
}
7
8
inview(entries, observer) {
9
entries.forEach(entry => {
10
if (!entry.intersectionRatio) return
11
12
entry.target.addEventListener('load', this.loading.bind(this))
13
entry.target.src = this.props.src
14
observer.unobserve(entry.target)
15
})
16
}
17
18
loading(event) {
19
if (event.target.complete)
20
this.setState({
21
loaded: true,
22
})
23
}
24
25
componentDidMount() {
26
this.setState({
27
loaded: false,
28
})
29
30
const observer = new IntersectionObserver(this.inview.bind(this))
31
32
observer.observe(this.element)
33
}
34
35
render() {
36
const { loaded } = this.state
37
const classList = (this.props.class ?? this.props.className)
38
.split(' ')
39
.filter(Boolean)
40
.concat(loaded ? this.props.classNameOnLoad.split(' ') : [])
41
.join(' ')
42
return (
43
<img className={classList} ref={element => (this.element = element)} />
44
)
45
}
46
}
47