/
on-loading-complete.js
127 lines (114 loc) · 3.06 KB
/
on-loading-complete.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import { useState } from 'react'
import Image from 'next/image'
const Page = () => {
// Hoisted state to count each image load callback
const [idToCount, setIdToCount] = useState({})
const [clicked, setClicked] = useState(false)
return (
<div>
<h1>On Loading Complete Test</h1>
<ImageWithMessage
id="1"
src="/test.jpg"
width="128"
height="128"
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<ImageWithMessage
id="2"
src={require('../public/test.png')}
placeholder="blur"
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<ImageWithMessage
id="3"
src="/test.svg"
width="1200"
height="1200"
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<ImageWithMessage
id="4"
src="/test.ico"
width={200}
height={200}
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<ImageWithMessage
id="5"
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAE0lEQVR42mNk+P+/ngEKGMngAADDdwx3Uz/3AAAAAABJRU5ErkJggg=="
width={64}
height={64}
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<ImageWithMessage
id="6"
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAE0lEQVR42mNk+P+/ngEKGMngAADDdwx3Uz/3AAAAAABJRU5ErkJggg=="
width={128}
height={128}
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<ImageWithMessage
id="7"
src="/test.bmp"
loading="eager"
width="400"
height="400"
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<ImageWithMessage
id="8"
src={clicked ? '/foo/test-rect.jpg' : '/wide.png'}
width="500"
height="500"
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<ImageWithMessage
id="9"
src={require('../public/test.png')}
placeholder="blur"
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<button id="toggle" onClick={() => setClicked(!clicked)}>
Toggle
</button>
<div id="footer" />
</div>
)
}
function ImageWithMessage({ id, idToCount, setIdToCount, ...props }) {
const [msg, setMsg] = useState('[LOADING]')
return (
<>
<div className="wrap">
<Image
id={`img${id}`}
onLoadingComplete={(img) => {
const { naturalWidth, naturalHeight, nodeName } = img
let count = idToCount[id] || 0
count++
idToCount[id] = count
setIdToCount(idToCount)
const name = nodeName.toLocaleLowerCase()
setMsg(
`loaded ${count} ${name}${id} with dimensions ${naturalWidth}x${naturalHeight}`
)
}}
{...props}
/>
</div>
<p id={`msg${id}`}>{msg}</p>
<hr />
</>
)
}
export default Page