I am dealing with a simple premise that questions viewport and based on that i am returning different aspectRatios. Now, for some reason i always have else return as true and then millisecond later the viewport gets validated. The result is that i am picking 2 aspect ratios and that makes me download additional image, which presents as unnecessary. I am wondering if there is a way around it, or to write it differently?
JavaScript
x
18
18
1
const getResponsiveAspectRatio = (): {
2
s: ValidRatios
3
m: ValidRatios
4
l: ValidRatios
5
} => {
6
if (viewport?.isWrapperWidthAndUp) {
7
return { s: "4-3", m: "4-3", l: "4-3" }
8
} else if (viewport?.isLargeDesktopAndUp) {
9
return { s: "1-1", m: "1-1", l: "1-1" }
10
} else if (viewport?.isDesktopAndUp) {
11
return { s: "3-4", m: "3-4", l: "3-4" }
12
} else if (viewport?.isTabletAndUp) {
13
return { s: "3-4", m: "3-4", l: "3-4" }
14
} else {
15
return { s: "1-1", m: "1-1", l: "1-1" }
16
}
17
}
18
Advertisement
Answer
Check for viewport explicitely first
JavaScript
1
24
24
1
const getResponsiveAspectRatio = (): {
2
s: ValidRatios
3
m: ValidRatios
4
l: ValidRatios
5
} => {
6
7
if (!viewport) {
8
// Viewport is not initialized
9
return null; // return null or some value that the calling code can
10
// handle and will not result in downloading resources
11
}
12
else if (viewport?.isWrapperWidthAndUp) {
13
return { s: "4-3", m: "4-3", l: "4-3" }
14
} else if (viewport?.isLargeDesktopAndUp) {
15
return { s: "1-1", m: "1-1", l: "1-1" }
16
} else if (viewport?.isDesktopAndUp) {
17
return { s: "3-4", m: "3-4", l: "3-4" }
18
} else if (viewport?.isTabletAndUp) {
19
return { s: "3-4", m: "3-4", l: "3-4" }
20
} else {
21
return { s: "1-1", m: "1-1", l: "1-1" }
22
}
23
}
24