### Initialize Perfume.js Library Source: https://context7.com/zizzamia/perfume.js/llms.txt Initializes the library with configuration options including resource timing and an analytics tracker callback. This setup is required to start observing Web Vitals and device information. ```javascript import { initPerfume } from 'perfume.js'; initPerfume({ resourceTiming: true, elementTiming: true, maxMeasureTime: 30000, analyticsTracker: (options) => { const { metricName, data, navigatorInformation } = options; if (['TTFB', 'FCP', 'LCP', 'FID', 'CLS', 'INP', 'TBT'].includes(metricName)) { console.log(`${metricName}: ${data}`); } } }); ``` -------------------------------- ### Install and Import Perfume.js Source: https://github.com/zizzamia/perfume.js/blob/master/docs/src/index.html Instructions for installing the library via npm and importing it into a project using standard ES modules or UMD bundles. ```bash npm install perfume.js --save ``` ```javascript import Perfume from 'perfume.js'; import Perfume from 'node_modules/perfume.js/perfume.umd.js'; ``` -------------------------------- ### Initialize Perfume.js with Custom Analytics Tracker Source: https://github.com/zizzamia/perfume.js/blob/master/CHANGELOG.md Demonstrates how to initialize Perfume.js using a functional approach, providing a custom analytics tracker function to send performance metrics to an external tool. This setup is suitable for tracking Critical User Journeys. ```javascript import { initPerfume } from 'perfume.js'; initPerfume({ analyticsTracker: ({ metricName, data }) => { myAnalyticsTool.track(metricName, data); }) }); ``` -------------------------------- ### Example Metric Output Formats Source: https://github.com/zizzamia/perfume.js/blob/master/README.md These snippets show the structure of the data reported by Perfume.js for navigation timing and first paint metrics. ```javascript // Perfume.js: navigationTiming { ... timeToFirstByte: 192.65 } // Perfume.js: fp 1482.00 ms ``` -------------------------------- ### Track User Journey Steps with Perfume.js Marks Source: https://github.com/zizzamia/perfume.js/blob/master/README.md This TypeScript example illustrates how to track user journey steps by marking the start and end of specific user actions or system processes. It uses `markStep` to define these boundaries, helping to measure system time during navigation or data loading, distinct from cognitive time. ```typescript // Marking the start of the step const ScreenA = () => { const handleNavigation = () => { ... // Navigation logic // Mark when navigating to screen B markStep('navigate_to_screen_B'); } ... return ( <> > ); } // Marking the end of the step const ScreenB = () => { const { viewer } = fetch("http://example.com/userInfo") .then((response) => response.json()) .then((data) => data); const {name} = viewer.userProperties; useEffect(() => { if (name) { // Mark when data is ready for screen B markStep('loaded_screen_B'); } }, [name]) ... } ``` -------------------------------- ### Marking Steps Source: https://github.com/zizzamia/perfume.js/blob/master/README.md Explains how to use the `markStep` function to denote the start and end points of defined steps. ```APIDOC ## MarkStep `markStep` is the function used to start and end steps in applications. ### Description Marks the beginning or end of a performance step. ### Request Example ```typescript // To mark the beginning of load_screen_B step markStep('navigate_to_screen_B'); ``` ``` -------------------------------- ### Implement Element Timing with Perfume.js Source: https://github.com/zizzamia/perfume.js/blob/master/README.md This example demonstrates how to use Perfume.js with the Element Timing API to track when specific HTML elements, like headings or images, are displayed on screen. By adding the `elementtiming` attribute to HTML elements, you can measure their rendering performance. ```html
```
```javascript
initPerfume({
elementTiming: true,
analyticsTracker: ({ metricName, data }) => {
myAnalyticsTool.track(metricName, data);
})
});
```
--------------------------------
### Marking User Journey Step Start with Perfume.js
Source: https://github.com/zizzamia/perfume.js/blob/master/docs/src/app/app.component.html
This snippet demonstrates how to mark the start of a user journey step. It uses the `markStep` function from Perfume.js, typically called when an action initiates a process, like tapping a button to navigate.
```javascript
const ScreenA = () => ({'{'}
const handleNavigation = () => {{'{'}}
// Navigation logic
// Mark when navigating to screen B
markStep('navigate_to_screen_B')
}
return (
)
})
```
--------------------------------
### start / end Custom Measurements
Source: https://context7.com/zizzamia/perfume.js/llms.txt
The `start()` and `end()` functions allow you to measure the duration of custom operations using the Performance API's mark and measure features. Use `start()` to begin timing and `end()` to complete the measurement and log the result.
```APIDOC
## start / end
### Description
The `start()` and `end()` functions allow you to measure the duration of custom operations using the Performance API's mark and measure features. Use `start()` to begin timing and `end()` to complete the measurement and log the result.
### Method
Custom Measurement (not an HTTP method)
### Endpoint
N/A
### Parameters
#### `start(markName: string)`
- **markName** (string) - Required - The name of the mark to start.
#### `end(markName: string, data?: object)`
- **markName** (string) - Required - The name of the mark to end.
- **data** (object) - Optional - Custom data to associate with the measurement.
### Request Example
```javascript
import { initPerfume, start, end } from 'perfume.js';
initPerfume({
analyticsTracker: ({ metricName, data }) => {
console.log(`${metricName}: ${data}ms`);
},
});
// Measure a custom operation
start('dataFetch');
const response = await fetch('/api/users');
const users = await response.json();
end('dataFetch');
// Measure a computation
start('fibonacci');
function fibonacci(n) {
return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}
fibonacci(30);
end('fibonacci');
// With custom properties
start('imageProcessing');
processImage(largeImage);
end('imageProcessing', { imageSize: '2048x1536', format: 'png' });
```
### Response
N/A (These functions trigger the `analyticsTracker` callback)
### Response Example
```
dataFetch: 245.32ms
fibonacci: 12.45ms
imageProcessing: 89.23ms (with custom attribution)
```
```
--------------------------------
### markStep / markStepOnce - User Journey Steps
Source: https://context7.com/zizzamia/perfume.js/llms.txt
Functions for tracking User Journey steps. `markStep()` creates a performance mark for step tracking, while `markStepOnce()` creates a mark only if one with the same name doesn't already exist. Steps measure the time between a start mark and an end mark to track user flow performance.
```APIDOC
## markStep / markStepOnce
### Description
Functions for tracking User Journey steps. `markStep()` creates a performance mark for step tracking, while `markStepOnce()` creates a mark only if one with the same name doesn't already exist. Steps measure the time between a start mark and an end mark to track user flow performance.
### Method
N/A (These are function calls within your application code)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```javascript
import { initPerfume, markStep, markStepOnce } from 'perfume.js';
const steps = {
load_home_screen: {
threshold: 'quick',
marks: ['navigate_to_home', 'loaded_home'],
},
};
initPerfume({
steps,
analyticsTracker: ({ metricName, data, attribution, rating }) => {
if (metricName === 'userJourneyStep') {
console.log(`Step: ${attribution.stepName}, Duration: ${data}ms, Rating: ${rating}`);
}
},
});
// Mark the start of a step
markStep('navigate_to_home');
// Mark the end of a step (e.g., when content is loaded)
// markStep('loaded_home');
// Use markStepOnce if a mark might be called multiple times
// markStepOnce('loaded_product');
```
### Response
N/A (These functions trigger performance metrics internally)
### Response Example
N/A
```
--------------------------------
### Measure Custom Operations with start and end
Source: https://context7.com/zizzamia/perfume.js/llms.txt
Uses the Performance API to measure the duration of specific code blocks or operations. The start() function begins the timer, and end() completes it, optionally accepting custom metadata.
```javascript
import { start, end } from 'perfume.js';
start('dataFetch');
const response = await fetch('/api/users');
end('dataFetch');
start('imageProcessing');
processImage(largeImage);
end('imageProcessing', { imageSize: '2048x1536' });
```
--------------------------------
### Track User Journey Steps with Perfume.js
Source: https://context7.com/zizzamia/perfume.js/llms.txt
Enables tracking of User Journey steps using `markStep` and `markStepOnce`. These functions create performance marks to measure the duration of user flows between defined start and end points. Configuration involves defining step thresholds and associated marks. The `initPerfume` function is used to set up step tracking and the `analyticsTracker` callback.
```javascript
import { initPerfume, markStep, markStepOnce } from 'perfume.js';
// Define step configurations with threshold tiers
const steps = {
load_home_screen: {
threshold: 'quick', // Thresholds: instant, quick, moderate, slow, unavoidable
marks: ['navigate_to_home', 'loaded_home'],
},
load_product_details: {
threshold: 'moderate',
marks: ['navigate_to_product', 'loaded_product'],
},
checkout_flow: {
threshold: 'slow',
marks: ['start_checkout', 'complete_checkout'],
},
};
initPerfume({
steps,
analyticsTracker: ({ metricName, data, rating, attribution }) => {
if (metricName === 'userJourneyStep') {
console.log(`Step: ${attribution.stepName}, Duration: ${data}ms, Rating: ${rating}`);
}
},
onMarkStep: (mark, activeSteps) => {
console.log(`Mark triggered: ${mark}, Active steps: ${activeSteps.join(', ')}`);
},
});
// In your navigation handler
function handleNavigateToHome() {
markStep('navigate_to_home');
router.push('/home');
}
// When home screen content is loaded
function HomeScreen() {
useEffect(() => {
if (contentLoaded) {
markStep('loaded_home');
}
}, [contentLoaded]);
}
// Output: Step: load_home_screen, Duration: 245ms, Rating: good
// Use markStepOnce when a mark may be called multiple times
function ProductImage({ onLoad }) {
return
```
```javascript
import { initPerfume } from 'perfume.js';
initPerfume({
elementTiming: true,
analyticsTracker: ({ metricName, data, attribution }) => {
if (metricName === 'ET') {
console.log(`Element "${attribution.identifier}" rendered at ${data}ms`);
analytics.track('element_timing', {
element: attribution.identifier,
renderTime: data,
});
}
},
});
```
--------------------------------
### clear Custom Measurements
Source: https://context7.com/zizzamia/perfume.js/llms.txt
Removes the named performance marks from the browser's performance entry buffer. Use this when you need to cancel a measurement that was started but should not be completed.
```APIDOC
## clear
### Description
Removes the named performance marks from the browser's performance entry buffer. Use this when you need to cancel a measurement that was started but should not be completed.
### Method
Clear Measurement (not an HTTP method)
### Endpoint
N/A
### Parameters
#### `clear(markName: string)`
- **markName** (string) - Required - The name of the mark to clear.
### Request Example
```javascript
import { initPerfume, start, end, clear } from 'perfume.js';
initPerfume({
analyticsTracker: ({ metricName, data }) => {
console.log(`${metricName}: ${data}ms`);
},
});
// Start measuring an operation
start('userAction');
// Cancel if the operation is aborted
if (userCancelled) {
clear('userAction');
return;
}
// Complete the measurement if not cancelled
end('userAction');
```
### Response
N/A (This function modifies the browser's performance buffer)
### Response Example
N/A
```
--------------------------------
### Initialize Perfume.js with Analytics Tracker
Source: https://github.com/zizzamia/perfume.js/blob/master/docs/src/app/app.component.html
This snippet demonstrates how to initialize Perfume.js and configure an analytics tracker to receive and process performance metrics. It includes a switch statement to handle different metric types and send them to a hypothetical 'myAnalyticsTool'.
```javascript
const perfume = new Perfume({
analyticsTracker: (options) => {
const { metricName, data, navigatorInformation } = options;
switch (metricName) {
case 'navigationTiming':
if (data && data.timeToFirstByte) {
myAnalyticsTool.track('navigationTiming', data);
}
break;
case 'networkInformation':
if (data && data.effectiveType) {
myAnalyticsTool.track('networkInformation', data);
}
break;
case 'TTFB':
myAnalyticsTool.track('timeToFirstByte', { duration: data });
break;
case 'FCP':
myAnalyticsTool.track('firstContentfulPaint', { duration: data });
break;
case 'FID':
myAnalyticsTool.track('firstInputDelay', { duration: data });
break;
case 'LCP':
myAnalyticsTool.track('largestContentfulPaint', { duration: data });
break;
case 'CLS':
myAnalyticsTool.track('cumulativeLayoutShift', { duration: data });
break;
case 'TBT':
myAnalyticsTool.track('totalBlockingTime', { duration: data });
break;
default:
myAnalyticsTool.track(metricName, { duration: data });
break;
}
}
});
```
--------------------------------
### Initialize Perfume.js with Resource Timing
Source: https://github.com/zizzamia/perfume.js/blob/master/docs/src/app/app.component.html
Configures the Perfume instance to track resource timing and report data via a custom analytics tracker. This enables monitoring of document-dependent resources and data consumption.
```javascript
const perfume = new Perfume({
resourceTiming: true,
analyticsTracker: ({ metricName, data }) => {
myAnalyticsTool.track(metricName, data);
}
});
```
--------------------------------
### Navigation Total Blocking Time (NTBT)
Source: https://github.com/zizzamia/perfume.js/blob/master/docs/src/app/app.component.html
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. Calling this method marks the start of a new NTBT measurement.
```APIDOC
## Navigation Total Blocking Time (NTBT)
### Description
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. Calling this method marks the start of a new NTBT measurement. If called before the 2s window ends, it interrupts the previous measurement.
### Method
`mark()`
### Endpoint
N/A
### Parameters
N/A
### Request Example
```javascript
const perfume = new Perfume({});
perfume.mark('navigation'); // Marks the start of the NTBT measurement
```
### Response
#### Success Response (200)
- **ntbt** (number) - Navigation Total Blocking Time in milliseconds.
#### Response Example
```json
{
"ntbt": 210.30
}
```
```
--------------------------------
### Development Commands
Source: https://github.com/zizzamia/perfume.js/blob/master/README.md
Lists the available npm scripts for developing and maintaining the Perfume.js library.
```APIDOC
## Develop
- `npm run test`: Run test suite
- `npm run build`: Generate bundles and typings
- `npm run lint`: Lints code
```
--------------------------------
### Perfume.js Default Options
Source: https://github.com/zizzamia/perfume.js/blob/master/README.md
Shows the default configuration options for the Perfume.js constructor.
```APIDOC
## Perfume custom options
Default options provided to Perfume.js constructor.
### Description
Lists the default configuration options available for Perfume.js initialization.
### Request Example
```javascript
const options = {
resourceTiming: false,
elementTiming: false,
analyticsTracker: options => {},
maxMeasureTime: 30000,
enableNavigtionTracking: true,
};
```
```
--------------------------------
### markNTBT - Navigation Total Blocking Time
Source: https://context7.com/zizzamia/perfume.js/llms.txt
Marks the start of Navigation Total Blocking Time (NTBT) measurement. NTBT measures the amount of time the application may be blocked from processing code during a 2-second window after navigation. Call this at the beginning of each navigation in your single-page application.
```APIDOC
## markNTBT
### Description
Marks the start of Navigation Total Blocking Time (NTBT) measurement. NTBT measures the amount of time the application may be blocked from processing code during a 2-second window after navigation. Call this at the beginning of each navigation in your single-page application.
### Method
N/A (This is a function call within your application code)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```javascript
import { initPerfume, markNTBT } from 'perfume.js';
initPerfume({
analyticsTracker: ({ metricName, data, rating }) => {
if (metricName === 'NTBT') {
console.log(`Navigation Total Blocking Time: ${data}ms (${rating})`);
}
},
});
// Call markNTBT() at the beginning of each navigation
markNTBT();
```
### Response
N/A (This function triggers performance metrics internally)
### Response Example
N/A
```
--------------------------------
### Monitor Resource Timing and Data Consumption
Source: https://context7.com/zizzamia/perfume.js/llms.txt
Shows how to enable resource timing to track individual asset performance and aggregate data consumption by type, allowing for monitoring of page weight.
```javascript
import { initPerfume } from 'perfume.js';
initPerfume({
resourceTiming: true,
analyticsTracker: ({ metricName, data }) => {
switch (metricName) {
case 'resourceTiming':
console.log('Resource:', data.name);
console.log('Duration:', data.duration);
console.log('Size:', data.decodedBodySize);
break;
case 'dataConsumption':
console.log('Data Consumption:', data);
if (data.total > 10000) {
console.warn('Page weight exceeds 10MB');
}
break;
}
},
});
```
--------------------------------
### Navigation Total Blocking Time (NTBT)
Source: https://github.com/zizzamia/perfume.js/blob/master/README.md
Measures the time the application may be blocked from processing code during the 2s window after a user navigates from page A to page B. It sums the blocking time of all long tasks in this window. This method can be called to mark the start of a navigation, potentially interrupting a previous measurement.
```APIDOC
## Navigation Total Blocking Time (NTBT)
### Description
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.
### Method
`perfume.markNTBT()`
### Endpoint
N/A (Client-side API)
### Parameters
None
### Request Example
```javascript
import { createBrowserHistory } from 'history';
export const history = createBrowserHistory();
initPerfume({
analyticsTracker: ({ metricName, data }) => {
myAnalyticsTool.track(metricName, data);
})
});
// React custom history
history.listen(() => {
// Measure NTBT at the beginning of each navigation
perfume.markNTBT();
});
```
### Response
#### Success Response (Implicit)
- The metric is tracked and sent to the `analyticsTracker`.
#### Response Example
```
// Perfume.js: ntbt 78 ms
```
```
--------------------------------
### Configure Perfume.js Steps
Source: https://github.com/zizzamia/perfume.js/blob/master/README.md
Defines and initializes performance tracking steps for Perfume.js. It requires defining step configurations with thresholds and marks, then passing them to the initPerfume function.
```typescript
export const steps = {
load_screen_A: {
threshold: ThresholdTier.quick,
marks: ['navigate_to_screen_A', 'loaded_screen_A'],
},
load_screen_B: {
threshold: ThresholdTier.quick,
marks: ['navigate_to_screen_B', 'loaded_screen_B'],
},
};
initPerfume({ steps });
```
--------------------------------
### Initialize Perfume.js Analytics Tracker
Source: https://github.com/zizzamia/perfume.js/blob/master/docs/src/app/app.component.html
Configures the Perfume.js library to track various performance metrics and report them to an external analytics tool.
```APIDOC
## Perfume.js Initialization
### Description
Initializes the Perfume.js instance with an `analyticsTracker` callback to handle performance metrics reporting.
### Method
Constructor
### Parameters
#### Request Body
- **analyticsTracker** (function) - Required - A callback function that receives metricName, data, and navigatorInformation to process and send to your analytics provider.
### Request Example
const perfume = new Perfume({
analyticsTracker: (options) => {
const { metricName, data } = options;
// Handle tracking logic here
}
});
### Response
#### Success Response (200)
- **perfume** (object) - The initialized Perfume instance.
```
--------------------------------
### Perfume.js Initialization with Web Vitals Attribution
Source: https://github.com/zizzamia/perfume.js/blob/master/CHANGELOG.md
Shows how to initialize Perfume.js with the updated analytics tracker format that includes attribution data, metric name, core vital data, and navigator information. This version leverages the Web Vitals library for enhanced metric reporting.
```typescript
new Perfume({
...
analyticsTracker: ({ attribution, metricName, data, navigatorInformation, rating }) => {
// Report the metric with your favorite analytics tool
}
});
```
--------------------------------
### Perfume.js Default Options
Source: https://github.com/zizzamia/perfume.js/blob/master/README.md
Shows the default configuration options for the Perfume.js constructor. These options can be customized during initialization to control various performance tracking features.
```javascript
const options = {
resourceTiming: false,
elementTiming: false,
analyticsTracker: options => {},
maxMeasureTime: 30000,
enableNavigtionTracking: true,
};
```
--------------------------------
### Enrich Metrics with Device and Network Information
Source: https://context7.com/zizzamia/perfume.js/llms.txt
This snippet demonstrates how to initialize Perfume.js and use the navigatorInformation object within the analyticsTracker. It shows how to segment metrics based on device capability and apply conditional performance budgets for low-end versus high-end devices.
```javascript
import { initPerfume } from 'perfume.js';
initPerfume({
analyticsTracker: ({ metricName, data, navigatorInformation }) => {
const segment = navigatorInformation.isLowEndExperience ? 'low-end' : 'high-end';
analytics.track(metricName, {
value: data,
segment,
deviceMemory: navigatorInformation.deviceMemory,
cpuCores: navigatorInformation.hardwareConcurrency,
swStatus: navigatorInformation.serviceWorkerStatus,
});
const budgets = navigatorInformation.isLowEndDevice
? { LCP: 4000, FID: 300, CLS: 0.25 }
: { LCP: 2500, FID: 100, CLS: 0.1 };
if (metricName === 'LCP' && data > budgets.LCP) {
console.warn(`LCP exceeded budget for ${segment} devices`);
}
},
});
```
--------------------------------
### Integrating with Google Analytics
Source: https://github.com/zizzamia/perfume.js/blob/master/README.md
Demonstrates how to use the `analyticsTracker` option to send performance metrics to Google Analytics.
```APIDOC
## 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.
### Description
Configures Perfume.js to send performance metrics as events to Google Analytics.
### Request Example
```javascript
const metricNames = ['TTFB', 'RT', 'FCP', 'LCP', 'FID', 'CLS', 'TBT'];
initPerfume({
analyticsTracker: ({ attribution, metricName, data, navigatorInformation, rating, navigationType }) => {
if (metricNames.includes(metricName)) {
ga('send', 'event', {
eventCategory: 'Perfume.js',
eventAction: metricName,
// Google Analytics metrics must be integers, so the value is rounded
eventValue: metricName === 'cls' ? data * 1000 : data,
eventLabel: navigatorInformation.isLowEndExperience ? 'lowEndExperience' : 'highEndExperience',
// Use a non-interaction event to avoid affecting bounce rate
nonInteraction: true,
});
}
})
});
```
To connect with additional analytics providers, checkout the [analytics plugin for Perfume.js](https://getanalytics.io/plugins/perfumejs/).
```
--------------------------------
### Performance Metrics Overview
Source: https://github.com/zizzamia/perfume.js/blob/master/docs/src/app/app.component.html
Details on the performance metrics collected by Perfume.js.
```APIDOC
## Performance Metrics
### Description
List of key performance metrics tracked by the library.
### Metrics
- **TTFB** (number) - Time To First Byte in milliseconds.
- **FCP** (number) - First Contentful Paint in milliseconds.
- **FID** (number) - First Input Delay in milliseconds.
- **LCP** (number) - Largest Contentful Paint in milliseconds.
- **CLS** (number) - Cumulative Layout Shift score.
- **TBT** (number) - Total Blocking Time in milliseconds.
### Data Enrichment
- **deviceMemory** (number) - RAM in GB.
- **hardwareConcurrency** (number) - Number of logical CPU cores.
- **isLowEndDevice** (boolean) - Calculated score based on RAM and CPU.
- **isLowEndExperience** (boolean) - Calculated score based on RAM, CPU, Network, and Data Saver settings.
```
--------------------------------
### Implement Element Timing Attribute
Source: https://github.com/zizzamia/perfume.js/blob/master/docs/src/app/app.component.html
Demonstrates how to add the elementtiming attribute to HTML elements to track their display time on screen using the Element Timing API.
```html