프론트엔드 개발자를 위한, 실전 웹 성능 최적화 Part.1 (인프런)
인프런 동영상 강의 내용을 요약 정리하면서 추가적으로 참고한 내용을 덧붙였습니다.
CSS Trigger 사이트를 참고하여 렌더링 비용을 고려하여 작업하는것이 좋다. (https://csstriggers.com/)
// without lazy
import OtherComponent from './OtherComponent';
// with lazy
const OtherComponent = React.lazy(() => import('./OtherComponent'));
//using suspense
import React, { Suspense } from 'react';
const OtherComponent = React.lazy(() => import('./OtherComponent'));
const MyComponent = () => {
return (
<div>
<Suspense fallback={<div>Loading ... </div>}>
<OtherComponent />
</Suspense>
</div>
);
}
const Home = lazy(() => import('./Home'));
const App = () => {
return (
// ...
<Route exact component={Home} path="/" />
);
}
import React, { Suspense, lazy } from 'react';
import { Switch, BrowserRouter as Router, Route } from 'react-router-dom';
const Home = lazy(() => import('./pages/Home'))
const SelectCity = lazy(() => import('./pages/SelectCity'))
const CityPage = lazy(() => import('./pages/City'))
const App = () => {
return (
<Router>
<Suspense fallback={<h1>Loading...</h1>}>
<Switch>
<Route exact component={Home} path="/" />
<Route component={SelectCity} path="/select-city" />
<Route component={CityPage} path="/:city" />
</Switch>
</Suspense>
</Router>
)
}
export default App;
function lazyWithPreload(importFunction) {
const Component = React.lazy(importFunction)
Component.preload = importFunction
return Component
}
const LazyImageModal = lazyWithPreLoad(() => import('./components/ImageModal'))
const App = () => {
// ...
useEffect(() => {
LazyImageModal.preload()
}, [])
const App = () => {
useEffect(() => {
const img = new Image()
img.scr = '이미지 주소'
}, [])
const cacheImages = async (scrArray) => {
const promises = await srcArray.map((src) => {
return new Promise(function (resolve, reject) {
const img = new Image()
img.src = src
img.onload = resolve()
img.onerror = reject()
})
})
await Promise.all(promises)
})
const App = () => {
useEffect(() => {
const imgs = ['image1.png', 'image2.png', 'image3.png']
cacheImages(imgs)
}, [])