@@ -2,6 +2,13 @@ async function loadProducts() {
2
2
const response = await fetch ( 'https://fakestoreapi.com/products' ) ;
3
3
const products = await response . json ( ) ;
4
4
displayProducts ( products ) ;
5
+ // Simulate heavy operation. It could be a complex price calculation.
6
+ const heavyOperationAsync = ( ) => {
7
+ for ( let i = 0 ; i < 10000000 ; i ++ ) {
8
+ const temp = Math . sqrt ( i ) * Math . sqrt ( i ) ;
9
+ }
10
+ heavyOperationAsync ( ) ;
11
+ } ;
5
12
}
6
13
7
14
const onIntersection = ( entries , observer ) => {
@@ -16,9 +23,25 @@ const onIntersection = (entries, observer) => {
16
23
17
24
const observer = new IntersectionObserver ( onIntersection , {
18
25
root : null , // 뷰포트
19
- threshold : 0.1 , // 10 %가 보이면 콜백 실행
26
+ threshold : 0.25 , // 25 %가 보이면 콜백 실행
20
27
} ) ;
21
28
29
+ const productsObserver = new IntersectionObserver (
30
+ ( entries , observer ) => {
31
+ entries . forEach ( ( entry ) => {
32
+ if ( entry . isIntersecting ) {
33
+ // #all-products .container가 뷰포트에 들어왔을 때만 실행
34
+ loadProducts ( ) ;
35
+ observer . unobserve ( entry . target ) ; // 한 번만 실행되도록 관찰 중지
36
+ }
37
+ } ) ;
38
+ } ,
39
+ {
40
+ root : null , // 뷰포트 사용
41
+ threshold : 0.1 , // 10%가 보일 때 실행
42
+ }
43
+ ) ;
44
+
22
45
function displayProducts ( products ) {
23
46
// Find the container where products will be displayed
24
47
const container = document . querySelector ( '#all-products .container' ) ;
@@ -76,14 +99,3 @@ function displayProducts(products) {
76
99
container . appendChild ( productElement ) ;
77
100
} ) ;
78
101
}
79
-
80
- loadProducts ( ) ;
81
-
82
- // Simulate heavy operation. It could be a complex price calculation.
83
- const heavyOperationAsync = ( ) => {
84
- for ( let i = 0 ; i < 10000000 ; i ++ ) {
85
- const temp = Math . sqrt ( i ) * Math . sqrt ( i ) ;
86
- }
87
- } ;
88
-
89
- requestIdleCallback ( heavyOperationAsync ) ;
0 commit comments