名詞解釋:
FCP: First Contentful Paint is when the browser renders the first DOM element on the page
FP: The browser renders the first bytes of information
let hiddenTime = document.visibilityState === 'hidden' ? 0 : Infinity;
document.addEventListener('visibilitychange', (evt) => {
hiddenTime = Math.min(hiddenTime, evt.timeStamp);
}, { once: true })
const FCPobserver = new PerformanceObserver((entryList) => {
entryList.getEntriesByName('first-contentful-paint').forEach(entry => {
if (entry.startTime < hiddenTime) {
trackingData.fcp = entry.startTime;
console.log('Record: FCP', trackingData.fcp);
}
})
}).observe({ type: 'paint', buffered: true });
標準:
<img loading="lazy" />
<script defer src="YouDontKnow"></script>
const observer = new PerformanceObserver((entryList) => {
const entries = entryList.getEntries();
entries.forEach(entry => {
trackingData.lcp = entry.startTime;
console.log('Record: LCP', trackingData.lcp);
})
}).observe({ type: 'largest-contentful-paint', buffered: true });
標準:
const CLSobserver = new PerformanceObserver((entryList) => {
const entries = entryList.getEntries();
for (const entry of entries) {
if (!entry.hadRecentInput) {
trackingData.cls += entry.value;
console.log('Record: CLS', trackingData.cls);
}
}
}).observe({ type: 'layout-shift', buffered: true });
標準:
How to improve CLS
FID measures the time from when a user first interacts with a page (i.e. when they click a link, tap on a button, or use a custom, JavaScript-powered control) to the time when the browser is actually able to begin processing event handlers in response to that interaction.
official document: https://vercel.com/docs/concepts/next.js/incremental-static-regeneration
簡單就是在過去我們在更新SSG的內容(因為是不常變動的)就要rebuild,因為SSG的頁面就是在build time產生出來,但是這樣如果有小部分要更新就要一直rebuild
-> ISR就是解決這問題,用法很像react-query的data flow, data超過時間就會轉為stale的cache
如何使用,加上revalidate就好
export async function getStaticProps() {
const res = await axios('http://localhost:4000/blogs');
return {
props: {
posts: res.data,
},
revalidate: 1,
}
}
補充 -> ISR是在server side的階段所以可以在這時候存取DB的資料,但是DB直接存取會有格式上的問題,所以建議還是建立一個server
DEMO TIME