New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

page-timing

Package Overview
Dependencies
Maintainers
3
Versions
34
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

page-timing

⏱ Collect and measure browser performance metrics

  • 3.1.5
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
5.8K
increased by1.08%
Maintainers
3
Weekly downloads
 
Created
Source

page-timing

⏱ Collect and measure browser performance metrics

All metrics are converted to snake_case

import { navigation, paint } from 'page-timing';

(async () => {
    const results = await Promise.all([
        paint(),
        navigation()
    ]);

    const metrics = Object.assign(...results);

    fetch('/browser-performance-metrics', {
        method: 'POST',
        body: JSON.stringify({
            page_name: 'my page',
            metrics
        }),
    });
})();

API endpoints

Metrics

NameMeaningGroupType
navigation_startTermination of previous document upon navigatingnavigationnumber
unload_event_startPrevious document unloadnavigationnumber
unload_event_endnavigationnumber
redirect_countNumbers of redirects while requesting this pagenavigationnumber
redirect_startRedirect from previous documentnavigationnumber
redirect_endnavigationnumber
fetch_startReady to fetch the documentnavigationnumber
domain_lookup_startnavigationnumber
domain_lookup_endnavigationnumber
durationDifference between responseEnd and startTimenavigationnumber
connect_startSent request to open a connectionnavigationnumber
connect_endnavigationnumber
secure_connection_startSecure connection handshakenavigationnumber
request_startRequest the documentnavigationnumber
response_startReceived the first byte of the responsenavigationnumber
response_endReceived the last byte of the responsenavigationnumber
dom_loadingParser started worknavigationnumber
dom_interactiveParser finished work on main document. Changed document readyState to "interactive"navigationnumber
dom_content_loaded_event_startExecuted required scripts after parsing the documentnavigationnumber
dom_content_loaded_event_endnavigationnumber
dom_completeChanged document readyState to "complete"navigationnumber
load_event_startAll assets are loaded. Document fires "load" eventnavigationnumber
load_event_endDocument finished executing "load" event listenersnavigationnumber
transfer_sizeSize (octets) of response headers and payload bodynavigationnumber
encoded_body_sizeSize (octets) of payload bodynavigationnumber
decoded_body_sizeSize (octets) of message bodynavigationnumber
worker_startTime until service worker rannavigationnumber
first_paintUser agent first rendered after navigationpaintnumber
first_contentful_paintDocument contains at least one element that is paintable and contentful †paintnumber
first_image_paintTBDpaintnumber
final_asset_javascript_countTotal number of Javascript resourcesassetsnumber
final_asset_javascript_loadLoading time spent on Javascript resourcesassetsnumber
final_asset_javascript_sizeTotal size of Javascript resourcesassetsnumber
final_asset_stylesheets_countTotal number of CSS resourcesassetsnumber
final_asset_stylesheets_loadLoading time spent on CSS resourcesassetsnumber
final_asset_stylesheets_sizeTotal size of CSS resourcesassetsnumber
final_asset_images_countTotal number of image resourcesassetsnumber
final_asset_images_loadLoading time spent on image resourcesassetsnumber
final_asset_images_sizeTotal size of image resourcesassetsnumber
final_asset_other_countTotal number of other resourcesassetsnumber
final_asset_other_loadLoading time spent on other resourcesassetsnumber
final_asset_other_sizeTotal size of other resourcesassetsnumber
connection_typebluetooth, cellular, ethernet, none, wifi, wimax, other, unknownconnectionstring
effective_bandwidthMbpsconnectionnumber
effective_connection_typeslow-2g, 2g, 3g, 4gconnectionstring
effective_max_bandwidthMbpsconnectionnumber
reduced_data_usageVendor's "Data Saver" feature enablesconnectionboolean
round_trip_timeEstimated effective round-trip in msconnectionnumber
navigation_typenavigate, reload, back_forward, prerenderconnectionstring
js_heap_size_limitMaximum bytes available for JS heapmemorynumber
total_js_heap_sizeTotal allocated bytes for JS heapmemorynumber
used_js_heap_sizeCurrently active bytes of JS heapmemorynumber
window_inner_heightHeight of the window's layout viewportdisplaynumber
window_inner_widthWidth of the window's layout viewportdisplaynumber
screen_color_depthColor depth of the screendisplaynumber
screen_pixel_depthBit depth of the screendisplaynumber
screen_orientation_typelandscape-primary, landscape-secondary, portrait-primary, portrait-secondarydisplaystring
final_dom_node_countTotal number of nodes under the document objectdomnumber
final_dom_nest_depthHighest nesting depth of DOM element under the documentdomnumber
final_html_sizeCharacter count of the HTML documentdomnumber
page_time_elapsedmilliseconds elapsed since the time originelapsednumber

contentful element: A visible element which contains non empty text, media content or input.

More functions

fps

Measure page frame rate at a certain point in time

import { fps } from 'page-timing';

const frames_per_second = await fps();
console.log({ frames_per_second });

Increase sample rate by checking more than one second. (Result is still in frames per second)

const frames_per_second = await fps({ sample: 5 });
console.log({ frames_per_second });

measure

Wrap a function and measure it's execution time in milliseconds into a performance measure entry.

import { measure } from 'page-timing';

async function myFunction(
    await wait(50);
    doSomethingElse();
}

await measure(myFunction, 'my-function');

// Example: Convert entries to a named array
Object.assign(
    ...performance.getEntriesByType('measure').map(
        ({ name, duration }) => ({[name]: duration})
    )
);
// {my-function: 53.35999990347773}

// Example: Retrieve a specific entry
const { duration } = performance.getEntriesByName('my-function');
// 53.35999990347773

Illustration of navigation events

Bonus

A simple example to add web vitals and TTI

npm i page-timing web-vitals tti-polyfill
import { all, connection } from 'page-timing';
import { getLCP, getFID, getCLS } from 'web-vitals';
import TTI from 'tti-polyfill';

(async () => {
    const connectionInfo = await connection();

    // Send metrics from browser performance API
    send(await all());

    // Send web vitals to the same endpoint
    [
        [getLCP, 'largest_contentful_paint'],
        [getFID, 'first_input_delay'],
        [getCLS, 'cumulative_layout_shift'],
    ].forEach(
        ([ fn, name ]) => fn(
            ({ value }) => send({
                [name]: value,
                ...connectionInfo // Some connection info
            })
        )
    );

    TTI.getFirstConsistentlyInteractive().then(
        (time_to_interactive) => send({
            time_to_interactive,
            ...connectionInfo // Some connection info
        })
    ).catch(() => null)
})();

const send = metrics => fetch('/browser-performance-metrics', {
  method: 'POST',
  body: JSON.stringify({ page_name: 'my page', metrics }),
});

Keywords

FAQs

Package last updated on 26 Apr 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc