Skip to content
This repository was archived by the owner on Jan 19, 2025. It is now read-only.

Commit 555c8fe

Browse files
committed
Continuer post 🚀
1 parent 04b9b5b commit 555c8fe

File tree

1 file changed

+37
-18
lines changed

1 file changed

+37
-18
lines changed
Lines changed: 37 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
layout: post
33
title: "Intersection Observer API: speed up your web applications with lazy loading"
4-
description: "Intersection Observer can improve your web applications performance and by helping you to implement lazy loading of images."
4+
description: "Intersection Observer can improve your web application performance by helping you to implement lazy loading of images."
55
date: 2019-05-10
66
image: /assets/images/posts/XXXXXX
77
tags: [web development, javascript, typescript]
@@ -20,53 +20,68 @@ One of the last thing that was contained in the report was a warning about offsc
2020

2121
{% include blog-lazy-image.html description="intersection observer offscreen audit" src="/assets/images/posts/intersection-observer-offscreen-audit.jpg" %}
2222

23-
So I followed the link contained in the report that points to a page where are contained the [official Google Guidelines about loading offscreen images](https://developers.google.com/web/tools/lighthouse/audits/offscreen-images). The main topic of the page is the [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) and how it can help you to load specific content only when it becomes visible in the viewport. I found also anothe article on the official Google developer website that explains in details how to leverage the power of Intersection Observer to lazy load the images in your web applications. So as you may imagine I "accepted the challenge" (like only [Barney Stinson](https://en.wikipedia.org/wiki/Barney_Stinson) in how I met your mother is used to do :stuck_out_tongue_winking_eye:) and I started to implement the lazy loading of images for my website.
23+
So I followed the link contained in the report that points to a page where are contained the [official Google Guidelines about loading offscreen images](https://developers.google.com/web/tools/lighthouse/audits/offscreen-images). The main topic of the page is the [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) and how it can help you to load specific content only when it becomes visible in the viewport. I found also anothe article on the official Google developer website that explains in details how to leverage the power of Intersection Observer to lazy load the images in your web applications. So as you may imagine I "accepted the challenge" (like only [Barney Stinson](https://en.wikipedia.org/wiki/Barney_Stinson) in how I met your mother is used to do :stuck_out_tongue_winking_eye:) and I started to implement the lazy load of images for my website.
2424

2525
#### Implementation
2626

27-
....
27+
First of all let's start by creating a function called `lazyLoadImages`. This function takes two parameter:
2828

29+
* selector, that is a string that I will use to select all the document [`Element`](https://developer.mozilla.org/en-US/docs/Web/API/Element "document element") objects that I want to observe
30+
* loadCompleted, a function that will be executed after the image has been downloaded
2931

30-
[Interserction Observer Polyfill](https://github.com/w3c/IntersectionObserver/tree/master/polyfill)
32+
This function will create a new instance of the `IntersectionObserver` object from the [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API). This object constructor takes two parementer:
33+
34+
* a callback, that is the function called when an object become visible given the current configuration
35+
* a configuration options, that let the developer customize how the Intersection Observer calculate the intersection with the viewport
36+
37+
After the cretion of the `IntersectionObserver` object I attached it to the DOM elements I want to observe by calling its `observer(element)` method on the document [`Element`](https://developer.mozilla.org/en-US/docs/Web/API/Element "document element") objects selected using [querySelectorAll](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll "document querySelectorAll") method with the `selector` received as parameter.
38+
39+
```javascript
40+
41+
const lazyLoadImages = (selector, loadCompleted) => {
42+
const intersectionObserver: IntersectionObserver = new IntersectionObserver(
43+
(entries, observer) => onIntersection(entries, observer, loadCompleted),
44+
{ rootMargin: '50px 0px', threshold: 0.01 }
45+
)
46+
document.querySelectorAll(selector).forEach(image => intersectionObserver.observe(image))
47+
}
48+
```
49+
50+
As you can see above from the snippet above, in the inserction callback I'm calling the `onIntersection` function. What does it do? ...
51+
52+
This is the final script.
3153

3254
```javascript
33-
/* @flow */
3455
import 'intersection-observer'
3556
import { removeCssClass } from './css-class'
3657

37-
const lazyLoadImages = (selector: string, loadCompleted: (image: HTMLImageElement) => void) => {
58+
const lazyLoadImages = (selector, loadCompleted) => {
3859
const intersectionObserver: IntersectionObserver = new IntersectionObserver(
39-
(entries: IntersectionObserverEntry[], observer: IntersectionObserver) => onIntersection(entries, observer, loadCompleted),
60+
(entries, observer) => onIntersection(entries, observer, loadCompleted),
4061
{ rootMargin: '50px 0px', threshold: 0.01 }
4162
)
4263
document.querySelectorAll(selector).forEach(image => intersectionObserver.observe(image))
4364
}
4465

45-
const onIntersection = (entries: IntersectionObserverEntry[], observer: IntersectionObserver, loadCompleted: (image: HTMLImageElement) => void) => {
66+
const onIntersection = (entries, observer, loadCompleted) => {
4667
entries.forEach(entry => {
4768
if (entry.intersectionRatio > 0) {
4869
observer.unobserve(entry.target)
49-
eventuallyLoadImage(entry.target, loadCompleted)
70+
loadImage(entry.target, loadCompleted)
5071
}
5172
})
5273
}
5374

54-
const eventuallyLoadImage = (element: HTMLElement, loadCompleted: (image: HTMLImageElement) => void) => {
55-
if (element instanceof HTMLImageElement) {
56-
loadImage(element, loadCompleted)
57-
}
58-
}
59-
60-
const loadImage = (image: HTMLImageElement, loadCompleted: (image: HTMLImageElement) => void) => {
61-
const src: string = image.dataset.src
75+
const loadImage = (image, loadCompleted) => {
76+
const src = image.dataset.src
6277
fetchImage(src).then(() => {
6378
image.src = src
6479
removeCssClass(image, 'lazy')
6580
loadCompleted(image)
6681
})
6782
}
6883

69-
const fetchImage = (src: string) => {
84+
const fetchImage = (src) => {
7085
return new Promise((resolve, reject) => {
7186
const image = new Image()
7287
image.src = src
@@ -78,6 +93,10 @@ const fetchImage = (src: string) => {
7893
export { lazyLoadImages }
7994
```
8095

96+
There's still one thing
97+
98+
[Interserction Observer Polyfill](https://github.com/w3c/IntersectionObserver/tree/master/polyfill)
99+
81100
#### Conclusion
82101

83102
Inteserction Observer is a powerful API. It let you implmenent lazy loading for rsources loading and reach performance and architectural application pattern that I had a chance to see only in mobile native apps. The web is filling the gap with native apps, and Intersection Observer are another demonstration that the 90% of the existing native mobile apps could become powerful web apps. As a consequence of the fact that in my daily job I'm still a native mobile app developer, I'm still following the iOS, Android and React Native scene and I'm still studying all the new tools and SDKs improvement released by Apple, Google and Facebook. But, you know, technology goes fast I have to be prepared for the future :relaxed:. Sooo, long live Intersection Observer!!! Web applications will be much more performant with your help :green_heart:.

0 commit comments

Comments
 (0)