You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Jan 19, 2025. It is now read-only.
As you can see above from the snippet above, in the inserction callback I'm calling the `onIntersection` function. What does it do? ...
50
+
As you can see above from the snippet above, in the inserction callback I'm calling the `onIntersection` function. What does it do? This function check the `IntersectionObserverEntry` received from the Intersection Observer as parameter: if a `target``Element` is inside the viewport it would have the `intersectionRatio` > 0. When this happen I can remove the observer and start the load of the image with the `loadImage` function.
The `loadImage` function downloads the image using the [Image](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image) object. At the end of the download I remove the `lazy` css class, that I used to hide the image until it has been download. Then the `loadCompleted` function is called, where the caller can do anything it want with the image (for example I'm doing a custom animation in order to avoid the `flash` effect when the image is show).
64
+
65
+
```javascript
66
+
constloadImage= (image, loadCompleted) => {
67
+
constsrc=image.dataset.src
68
+
fetchImage(src).then(() => {
69
+
image.src= src
70
+
removeCssClass(image, 'lazy')
71
+
loadCompleted(image)
72
+
})
73
+
}
74
+
75
+
constfetchImage= (src) => {
76
+
returnnewPromise((resolve, reject) => {
77
+
constimage=newImage()
78
+
image.src= src
79
+
image.onload= resolve
80
+
image.onerror= reject
81
+
})
82
+
}
83
+
```
84
+
85
+
This is the final script with the complete flow.
53
86
54
87
```javascript
55
88
import'intersection-observer'
@@ -93,9 +126,13 @@ const fetchImage = (src) => {
93
126
export { lazyLoadImages }
94
127
```
95
128
96
-
There's still one thing
129
+
There's still one thing that I didn't discuss yet. How can we support this type of lazy loading for the browser that doesn't still have implemented the `IntersectionObserver` API? The answer is the [Interserction Observer Polyfill](https://github.com/w3c/IntersectionObserver/tree/master/polyfill). I installed as a dependency of my project.
This [polyfill](https://en.wikipedia.org/wiki/Polyfill_(programming)"polyfill programming") exposes an ad hoc implementation in vanilla javascript of the Intersection Observer, or it exposes the current browser implementation if it is already in place for the browser that the user is using.
0 commit comments