利用 Perfume.js 與 Google Analytics 來做 Real User Monitoring
22 Sep 2020什麼是 Real User Monitoring?
Real User Monitoring 是指監測真正的使用者在操作網站功能的效能並搜集與分析資料,目的是了解產品的長期走向,可提供管理者更高階的決策需求。優點是能做到全方位監測、能找出真實的困境,缺點是需要流量、缺乏測試基準 。
點此看 Real User Monitoring (RUM) 與 Synthetic Monitoring (STM) 的比較。
以下利用 Perfume.js 與 Google Analytics 來做 Real User Monitoring。

安裝與設定
需要安裝 Perfume.js 與 ReactGA。
- Perfume.js 是使用瀏覽器通用的 Performance API 所實作的網頁效能監測工具,協助計算用於衡量使用者面向的效能評估的指標的值。
 - ReactGA 是提供在 React 框架下的 Google Analytics 模組。Perfume.js 計算完成後會經由 ReactGA 丟到 Google Analytics 報表。
 
設定方式如下,可在通用模組把 ReactGA 與 Perfume.js 包進來。
import ReactGA from 'react-ga';
import Perfume from 'perfume.js';
初始化 Performe.js,設定將 Performe.js 的計算結果存到 Google Analytics。
const analyticsTracker = function ({ metricName, data, duration }) {
  const METRICS = [
    // 選取要採集的指標
    'fp',
    'fcp',
    'fid',
    'lcp',
    'cls',
    'tbt',
  ];
  if (METRICS.includes(metricName)) {
    const duration = Math.round(Number(data));
    ReactGA.timing({
      category: 'performance by perfume (timing)',
      variable: metricName,
      value: duration, // in milliseconds
    });
  }
};
const perfume = new Perfume({
  firstPaint: true,
  firstContentfulPaint: true,
  firstInputDelay: true,
  timeToInteractive: true,
  logging: true,
  googleAnalytics: {
    enable: true,
    timingVar: 'userId',
  },
  analyticsTracker,
});
在 componentDidMount 時初始化 Google Analytics。
ReactGA.initialize('UA-123456789', {
  gaOptions: {
    userId, // 可從伺服器端取得目前使用者 ID 或其他可辨別的資料
  },
});
若想紀錄 pageview 可在 componentDidUpdate 時監測,判斷是否換頁,主要是參考這裡的作法。
componentDidUpdate({ location: prevLocation }) {
  const { location: { pathname, search }} = this.props;
  const isDifferentPathname = pathname !== prevLocation.pathname;
  const isDifferentSearch = search !== prevLocation.search;
  if (isDifferentPathname || isDifferentSearch) {
    this.logPageChange(pathname, search);
  }
}
logPageChange(pathname, search = '') {
  const page = pathname + search;
  const { location } = window;
  ReactGA.set({
    page,
    location: `${location.origin}${page}`,
    ...this.props.options,
  });
  ReactGA.pageview(page);
}
完成以上設定,等待一段時間後便可在「行為 > 網站速度 > 使用者載入時間」看到紀錄。
檢視報表
前往「行為 > 網站速度 > 使用者載入時間」查看紀錄,點進去任一「計時分類 (timingCategory)」來看「計時變數 (timingVariable)」。

計時變數 (timingVariable) 即是之前設定的 metrics,例如:First Contentful Paint (FCP) 等。如下圖所示,平均每個 session 的 FCP 是 2.14 秒。

疑難雜症
第一個問題是設定後過了快一天都看不到這個報表,好在等到第二天終於出現了,真的很需要耐心等待。這個問題也有人在 stackoverflow 問過-看這裡。
第二的問題是一開始我用 event 的方式來送 metric 的資料,意即「ReactGA.event」,導致出現 value 只能收整數而必須先做四捨五入,或是需要考慮選適合的貨幣單位;但正確的做法是用 timing 的方式,也就是「ReactGA.timing」,這樣在送的時候就是送 ms 而報表上就會出現秒了。
參考資料
- Real User Monitoring (RUM) vs. Synthetic Monitoring Comparison
 - Time to Interactive with RUM (Use Lighthouse for RUM?):使用 Perfume.js + GA 來做 RUM 的範例。
 - RUM and Google Analytics: What’s the difference
 - Error running Perfume.js: TypeError: Failed to execute ‘observe’ on ‘PerformanceObserver’:Perfume.js 範例。
 - First (Contentful) Paint with a touch of Perfume(.js)
 - johnnolan.dev Performance Dashboard
 - When Users Click: Tracking First Input Delay