Perfume.js

Web performance library for measuring all performance vitals metrics

README

  <img src="https://github.com/Zizzamia/perfume.js/blob/master/docs/src/assets/perfume-logo-v5-0-0.png"
  align="left" width="200" alt="Perfume.js logo" />

[![Current version](https://img.shields.io/github/tag/zizzamia/perfume.js?color=3498DB&label=version)](https://www.npmjs.org/package/perfume.js) [![Test Coverage](https://api.codeclimate.com/v1/badges/f813d2f45b274d93b8c5/test_coverage)](https://codeclimate.com/github/Zizzamia/perfume.js/test_coverage) No dependencies [![Build Status](https://travis-ci.org/Zizzamia/perfume.js.svg?branch=master)](https://travis-ci.org/Zizzamia/perfume.js) [![NPM Downloads](http://img.shields.io/npm/dm/perfume.js.svg)](https://www.npmjs.org/package/perfume.js) [![gzip size](https://img.badgesize.io/https://unpkg.com/perfume.js?compression=gzip&label=JS+gzip+size)](https://unpkg.com/perfume.js) [![brotli size](https://img.badgesize.io/https://unpkg.com/perfume.js?compression=brotli&label=JS+brotli+size)](https://unpkg.com/perfume.js)

<b>Page Speed</b> is a feature, and to deliver it we need to understand the many factors and fundamental limitations that are at play. If we can measure it, we can improve it.






Why Perfume.js?


Perfume is a tiny, web performance monitoring library that reports field data back to your favorite analytics tool.

- ⏰ Supports latest Performance APIs for precise metrics
- 🚀 Device data enrichment
- 🔨 Cross browser tested
- 🚿 Filters out false positive/negative results
- 🤙 Only 5.1Kb gzip
- 🏅 Web Vitals Score
- 🛰 Flexible analytics tool
- ⚡️ Waste-zero ms with requestIdleCallback strategy built-in


The latest in metrics & Real User Measurement


Perfume leverages the latest Performance APIs to collect field data that allows us to understand what real-world users are actually experiencing.

- Navigation Timing
- Navigator Interface
- Resource Timing
- Element Timing
- Service Worker Status
- StorageManager interface
- Time to First Byte (TTFB)
- First Contentful Paint (FCP)
- Largest Contentful Paint (LCP)
- First Input Delay (FID)
- Cumulative Layout Shift (CLS)
- Interaction to Next Paint (INP)
- Total Blocking Time (TBT)
- Navigation Total Blocking Time (NTBT)

At Coinbase, we use Perfume.js to capture a high-level scoring system that is clear, trusted, and easy to understand.


Summarizing the performance health of an application into a reliable and consistent score helps increase urgency and directs company attention and resources towards addressing each performance opportunity.

Perfume.js vs Web Vitals


Perfume leverages the Web Vitals library to collect all the standardized performance metrics. It explores new metrics like Navigation Total Blocking Time and dimensions like Low-End Devices, Service Worker status to understand your data better.

So don't worry, Perfume.js is a superset of Web Vitals, a bit like Typescript is a superset of Javascript.

Installing


npm (https://www.npmjs.com/package/perfume.js):

    npm install perfume.js --save

Importing library


You can import the generated bundle to use the whole library generated:

  1. ``` js
  2. import Perfume from 'perfume.js';
  3. ```

Universal Module Definition:

  1. ``` js
  2. import Perfume from 'node_modules/perfume.js/dist/perfume.umd.min.js';
  3. ```

Quick start


Metrics like Navigation Timing, Network Information, TTFB, FCP, FID, LCP, CLS, INP and TBT are default reported with Perfume; All results will be reported to the analyticsTracker callback, and the code below is just one way for you to organize your tracking, feel free to tweak it suit your needs.

🚀 Visit perfumejs.com for a live demo on how the metrics work. 🌕

  1. ``` js
  2. const perfume = new Perfume({
  3.   analyticsTracker: options => {
  4.     const {
  5.       attribution,
  6.       metricName,
  7.       data,
  8.       navigatorInformation,
  9.       rating
  10.     } = options;
  11.     switch (metricName) {
  12.       case 'navigationTiming':
  13.         if (data && data.timeToFirstByte) {
  14.           myAnalyticsTool.track('navigationTiming', data);
  15.         }
  16.         break;
  17.       case 'networkInformation':
  18.         if (data && data.effectiveType) {
  19.           myAnalyticsTool.track('networkInformation', data);
  20.         }
  21.         break;
  22.       case 'storageEstimate':
  23.         myAnalyticsTool.track('storageEstimate', data);
  24.         break;
  25.       case 'TTFB':
  26.         myAnalyticsTool.track('timeToFirstByte', { duration: data });
  27.         break;
  28.       case 'RT':
  29.         myAnalyticsTool.track('redirectTime', { duration: data });
  30.         break;
  31.       case 'FCP':
  32.         myAnalyticsTool.track('firstContentfulPaint', { duration: data });
  33.         break;
  34.       case 'FID':
  35.         myAnalyticsTool.track('firstInputDelay', { duration: data });
  36.         break;
  37.       case 'LCP':
  38.         myAnalyticsTool.track('largestContentfulPaint', { duration: data });
  39.         break;
  40.       case 'CLS':
  41.         myAnalyticsTool.track('cumulativeLayoutShift', { value: data });
  42.         break;
  43.       case 'INP':
  44.         myAnalyticsTool.track('interactionToNextPaint', { value: data });
  45.         break;
  46.       case 'TBT':
  47.         myAnalyticsTool.track('totalBlockingTime', { duration: data });
  48.         break;
  49.       case 'elPageTitle':
  50.         myAnalyticsTool.track('elementTimingPageTitle', { duration: data });
  51.         break;
  52.       default:
  53.         myAnalyticsTool.track(metricName, { duration: data });
  54.         break;
  55.     }
  56.   },
  57. });
  58. ```

In a world with widely varying device capabilities, a one-size-fits-all event doesn’t always work. Perfume adds data enrichment to all events so we can better understand the real world experiences:

- deviceMemory: the user's device memory (RAM).
- hardwareConcurrency: the number of logical CPU processor cores on the user's device.
- serviceWorkerStatus: status of the service worker between controlled, supported and unsupported.

Based on the Navigator APIs the library can help us differentiate between a low-end and a high-end device/experience:

- isLowEndDevice: combination of the score of RAM and CPU.
- isLowEndExperience: combination of the score of RAM, CPU, NetworkStatus and SaveData.

Performance audits


Coo coo coo cool, let's learn something new.

Navigation Timing


Navigation Timing collects performance metrics for the life and timings of a network request.

Perfume helps expose some of the key metrics you might need.

  • Redirect time: Page redirects aren't totally inconsequential, but they might not be something you run into very often. Still, redirects add latency to requests, so measuring them may be worth the effort.
  • DNS lookup: When a user requests a URL, the Domain Name System (DNS) is queried to translate a domain to an IP address.
  • Header size: HTTP header size
  • Fetch time: Cache seek plus response time
  • Worker time: Service worker time plus response time
  • Total time: Request plus response time (network only)
  • Download time: Response time only (download)
  • Time to First Byte: The amount of time it takes after the client sends an HTTP GET request to receive the first byte of the requested resource from the server. It is the largest web page load time component taking 40 to 60% of total web page latency.

  1. ``` js
  2. // Perfume.js: navigationTiming { ... timeToFirstByte: 192.65 }
  3. ```

First Paint (FP)


FP is the exact time taken for the browser to render anything as visually different from what was on the screen before navigation, e.g. a background change after a long blank white screen time.

  1. ``` js
  2. // Perfume.js: fp 1482.00 ms
  3. ```

First Contentful Paint (FCP)


FCP is the exact time taken for the browser to render the first bit of content from the DOM, which can be anything from an important image, text, or even the small SVG at the bottom of the page.

  1. ``` js
  2. // Perfume.js: fcp 2029.00 ms
  3. ```

Largest Contentful Paint (LCP)


LCP is an important, user-centric metric for measuring perceived load speed because it marks the point in the page load timeline when the page's main content has likely loaded—a fast LCP helps reassure the user that the page is useful.

We end the Largest Contentful Paint measure at two points: when First Input Delay happen and when the page's lifecycle state changes to hidden.

  1. ``` js
  2. // Perfume.js: lcp 2429.00 ms
  3. ```

First Input Delay (FID)


FID measures the time from when a user first interacts with your site (i.e. when they click a link, tap on a button) to the time when the browser is actually able to respond to that interaction.

  1. ``` js
  2. // Perfume.js: fid 3.20 ms
  3. ```

Cumulative Layout Shift (CLS)


CLS is an important, user-centric metric for measuring visual stability because it helps quantify how often users experience unexpected layout shifts—a low CLS helps ensure that the page is delightful.

We end the Cumulative Layout Shift measure at two points: when First Input Delay happen and when the page's lifecycle state changes to hidden.

  1. ``` js
  2. // Perfume.js: cls 0.13
  3. ```

Total Blocking Time (TBT)


TBT is an important, user-centric metric for measuring load responsiveness because it helps quantify the severity of how non-interactive a page is prior to it becoming reliably interactive—a low TBT helps ensure that the page is usable.

We end the Total Blocking Time measure 10 seconds after FID.

  1. ``` js
  2. // Perfume.js: tbt 347.07 ms
  3. ```

Navigation Total Blocking Time (NTBT)


This metric measures the amount of time the application may be blocked from processing code during the 2s window after a user navigates from page A to page B. The NTBT metric is the summation of the blocking time of all long tasks in the 2s window after this method is invoked.

Because this library is navigation agnostic, we have this method to mark when the navigation starts.

If this method is called before the 2s window ends; it will trigger a new NTBT measurement and interrupt the previous one.

  1. ``` js
  2. import { createBrowserHistory } from 'history';
  3. export const history = createBrowserHistory();

  4. const perfume = new Perfume({
  5.   analyticsTracker: ({ metricName, data }) => {
  6.     myAnalyticsTool.track(metricName, data);
  7.   })
  8. });

  9. // React custom history
  10. history.listen(() => {
  11.   // Measure NTBT at the beginning of each navigation
  12.   perfume.markNTBT();
  13. });

  14. // Perfume.js: ntbt 78 ms
  15. ```

Resource Timing


Resource Timing collects performance metrics for document-dependent resources. Stuff like style sheets, scripts, images, et cetera.
Perfume helps expose all PerformanceResourceTiming entries and groups data data consumption by Kb used.

  1. ``` js
  2. const perfume = new Perfume({
  3.   resourceTiming: true,
  4.   analyticsTracker: ({ metricName, data }) => {
  5.     myAnalyticsTool.track(metricName, data);
  6.   })
  7. });
  8. // Perfume.js: dataConsumption { "css": 185.95, "fetch": 0, "img": 377.93, ... , "script": 8344.95 }
  9. ```

Annotate metrics in the DevTools


Performance.mark (User Timing API) is used to create an application-defined peformance entry in the browser's performance entry buffer.

  1. ``` js
  2. const perfume = new Perfume({
  3.   analyticsTracker: ({ metricName, data }) => {
  4.     myAnalyticsTool.track(metricName, data);
  5.   })
  6. });
  7. perfume.start('fibonacci');
  8. fibonacci(400);
  9. perfume.end('fibonacci');
  10. // Perfume.js: fibonacci 0.14 ms
  11. ```

Performance Mark

Component First Paint


This metric mark the point, immediately after creating a new component, when the browser renders pixels to the screen.

  1. ``` js
  2. const perfume = new Perfume({
  3.   analyticsTracker: ({ metricName, data }) => {
  4.     myAnalyticsTool.track(metricName, data);
  5.   })
  6. });
  7. perfume.start('togglePopover');
  8. $(element).popover('toggle');
  9. perfume.endPaint('togglePopover');
  10. // Perfume.js: togglePopover 10.54 ms
  11. ```

Performance

Element Timing


Track when image elements and text nodes are displayed on screen using the emerging Element Timing API specification by simply adding theelementtiming attribute with a descriptive value of your choice to HTML elements you would like to measure:

  1. ``` html
  2. <h1 elementtiming="elPageTitle" class="title">Perfume.js</h1>
  3. <img
  4.   elementtiming="elHeroLogo"
  5.   alt="Perfume.js logo"
  6.   src="https://zizzamia.github.io/perfume/assets/perfume-logo-v5-0-0.png"
  7. />
  8. ```

  1. ``` js
  2. const perfume = new Perfume({
  3.   elementTiming: true,
  4.   analyticsTracker: ({ metricName, data }) => {
  5.     myAnalyticsTool.track(metricName, data);
  6.   })
  7. });

  8. // Perfume.js: elPageTitle 256.00 ms
  9. // Perfume.js: elHeroLogo 1234.00 ms
  10. ```

Web Vitals Score


Perfume will expose for all major metrics the vitals score, those can be used to improve your SEO and Google page rank.

WebGoodNeedsPoor
----------------------------------------------:----------------:--------:
Time0-800801-1800Over
Redirect0-100101-200Over
First0-20002001-4000Over
Largest0-25002501-4000Over
First0-100101-300Over
Cumulative0-0.10.11-0.25Over
Interaction0-200201-500Over
Total0-200201-600Over
Navigation0-200201-600Over

Perfume custom options


Default options provided to Perfume.js constructor.

  1. ``` js
  2. const options = {
  3.   resourceTiming: false,
  4.   elementTiming: false,
  5.   analyticsTracker: options => {},
  6.   maxMeasureTime: 30000,
  7. };
  8. ```

Use Google Analytics


A quick way to see your page speed results on your web app is by using Google Analytics. Those GA events will show on Behavior > Site Speed > User Timings. For testing you might want to see them coming live on Realtime > Events.

Have fun ✨

  1. ``` js
  2. const metricNames = ['TTFB', 'RT', 'FCP', 'LCP', 'FID', 'CLS', 'TBT'];
  3. new Perfume({
  4.   analyticsTracker: ({ attribution, metricName, data, navigatorInformation, rating }) => {
  5.     if (metricNames.includes(metricName)) {
  6.       ga('send', 'event', {
  7.         eventCategory: 'Perfume.js',
  8.         eventAction: metricName,
  9.         // Google Analytics metrics must be integers, so the value is rounded
  10.         eventValue: metricName === 'cls' ? data * 1000 : data,
  11.         eventLabel: navigatorInformation.isLowEndExperience ? 'lowEndExperience' : 'highEndExperience',
  12.         // Use a non-interaction event to avoid affecting bounce rate
  13.         nonInteraction: true,
  14.       });
  15.     }
  16.   })
  17. });
  18. ```

To connect with additional analytics providers, checkout the analytics plugin for Perfume.js.

Develop


- npm run test: Run test suite
- npm run build: Generate bundles and typings
- npm run lint: Lints code

Plugins



Perfume is used by


- Add your company name :)

Credits and Specs


Made with ☕️ by @zizzamia and
I want to thank some friends and projects for the work they did:

- Leraging the Performance Metrics that Most Affect User Experience for documenting this new User-centric performance metrics;ev
- Performance Timeline Level 2 the definition of _PerformanceObserver_ in that specification;
- The Contributors for their much appreciated Pull Requests and bug reports;
- you for the star you'll give this project 😉 and for supporting me by giving my project a try 😄

Contributors


This project exists thanks to all the people who contribute.

Backers


Thank you to all our backers! 🙏 [Become a backer]


Copyright and license


Code and documentation copyright 2022 Leonardo Zizzamia. Code released under the MIT license. Docs released under Creative Commons.

Team



Leonardo Zizzamia