JaeYeopHan / tip-archive

๐Ÿ“ฆ Archiving various development tips. If you watch this repository, you can get issues related to the newly registered development tip from the GitHub feed.
https://www.facebook.com/Jbee.dev/
245 stars 8 forks source link

PerformanceObserver / PerformancePaintTiming API #52

Open JaeYeopHan opened 5 years ago

JaeYeopHan commented 5 years ago

Catch FCP

๐Ÿ’กFCP: First Contentful Painting

๋ธŒ๋ผ์šฐ์ €๋Š” ์ผ๋ จ์˜ ๊ณผ์ •์„ ํ†ตํ•ด ํ™”๋ฉด์„ ๋ Œ๋”๋งํ•œ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๊ทธ ๊ณผ์ • ์ค‘์—๋Š” paint ๊ณผ์ •์ด ์žˆ์œผ๋ฉฐ ๋ณดํ†ต UX์™€ ๊ด€๋ จ๋œ ์„ฑ๋Šฅ ์ง€ํ‘œ๋กœ First Contentful Painting Time์„ ์‚ผ๋Š”๋‹ค. ์ด ์‹œ์ ์„ JavaScript๋กœ ์žก์•„๋‚ผ ์ˆ˜ ์žˆ์„๊นŒ? ์ด ์‹œ์ ์„ ์žก์•„๋‚ผ ์ˆ˜ ์žˆ๋‹ค๋ฉด React Application ์™ธ๋ถ€์—์„œ ReactDOM.render๊ฐ€ ์™„๋ฃŒ๋œ ์‹œ์ ์„ ์•Œ ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ?

PerformanceObserver

const po = new PerformanceObserver(list =>
  list
    .getEntries()
    .filter(({ entryType }) => entryType === 'paint')
    .map(({ name }) => name === FIRST_CONTENTFUL_PAINT)
    .forEach(/* callback */),
)

try {
  po.observe({ entryTypes: ['measure', 'paint'] })
} catch (e) {
  console.error(e)
  po.disconnect()
}

PerformanceObserver๋ผ๋Š” API๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ธŒ๋ผ์šฐ์ €๊ฐ€ ๊ทธ๋ ค์ง€๋Š” ๊ณผ์ •๋“ค์„ observeํ•  ์ˆ˜ ์žˆ๋‹ค. ์šฐ๋ฆฌ์—๊ฒŒ ํ•„์š”ํ•œ ์ธก์ • ์ง€ํ‘œ๋Š” paint ์‹œ์ ์ด๋‹ค. ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— observe์˜ parameter๋กœ { entryTypes: ['paint'] }๋งŒ ๋„˜๊ฒจ์ค˜๋„ ๋œ๋‹ค.

(์™œ try-catch๋กœ ๊ฐ์‹ธ์คฌ๋Š”์ง€๋Š” ๋ฐ”๋กœ ๋ฐ‘์—์„œ๐Ÿ‘‡)

PerformancePaintTiming

โ›‘ Safari ๋ฏธ์ง€์› API ๐Ÿคฆโ€โ™‚๏ธ

ํ•ด๋‹น API๋Š” Chrome์—์„œ๋งŒ ์ง€์›ํ•˜๊ณ  Safari์—์„œ๋Š” ์ง€์›ํ•˜์ง€ ์•Š๋Š”๋‹ค. ๋•Œ๋ฌธ์— entryType์—์„œ paint๋ฅผ observeํ•  ์ˆ˜ ์—†๋‹ค. paint๋ฅผ ๊ตฌ๋…ํ–ˆ์„ ๋•Œ ๋ฐ˜ํ™˜๋˜๋Š” entry์˜ interface๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

interface PerformancePaintTiming {
  name: string; // "first-paint" or "first-contentful-paint"
  entryType: string // "paint"
  duration: number
  startTime: number
}

So What?

ReactDOM.render๊ฐ€ ์™„๋ฃŒ๋œ ์‹œ์ ์„ ์žก๊ธฐ ์œ„ํ•ด PerformanceObserver API๋ฅผ ์‚ฌ์šฉํ–ˆ์ง€๋งŒ safari์—์„œ ๋ฏธ์ง€์›ํ•˜๋ฏ€๋กœ ํ„ฐ์ง„๋‹ค. ๋•Œ๋ฌธ์— safari๋ฅผ ํฌ๊ธฐํ•˜๊ณ  try-catch statement๋กœ ๊ฐ์‹ธ๋˜๊ฐ€ ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์„ ์ฐพ์•„์•ผ ํ•œ๋‹ค.