Skip to content

Commit 2fce7b0

Browse files
committed
Use intersection observer when polyfilled after gatsby-image first load
1 parent 59a5bbe commit 2fce7b0

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed

packages/gatsby-image/src/index.js

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -36,27 +36,32 @@ const inImageCache = props => {
3636

3737
let io
3838
const listeners = []
39-
if (typeof window !== `undefined` && window.IntersectionObserver) {
40-
io = new window.IntersectionObserver(
41-
entries => {
42-
entries.forEach(entry => {
43-
listeners.forEach(l => {
44-
if (l[0] === entry.target) {
45-
// Edge doesn't currently support isIntersecting, so also test for an intersectionRatio > 0
46-
if (entry.isIntersecting || entry.intersectionRatio > 0) {
47-
io.unobserve(l[0])
48-
l[1]()
39+
40+
function getIO() {
41+
if (typeof io === `undefined` && typeof window !== `undefined` && window.IntersectionObserver) {
42+
io = new window.IntersectionObserver(
43+
entries => {
44+
entries.forEach(entry => {
45+
listeners.forEach(l => {
46+
if (l[0] === entry.target) {
47+
// Edge doesn't currently support isIntersecting, so also test for an intersectionRatio > 0
48+
if (entry.isIntersecting || entry.intersectionRatio > 0) {
49+
io.unobserve(l[0])
50+
l[1]()
51+
}
4952
}
50-
}
53+
})
5154
})
52-
})
53-
},
54-
{ rootMargin: `200px` }
55-
)
55+
},
56+
{ rootMargin: `200px` }
57+
)
58+
}
59+
60+
return io
5661
}
5762

5863
const listenToIntersections = (el, cb) => {
59-
io.observe(el)
64+
getIO().observe(el)
6065
listeners.push([el, cb])
6166
}
6267

0 commit comments

Comments
 (0)