UNPKG

@sv-use/core

Version:

A collection of Svelte 5 utilities.

58 lines (57 loc) 1.66 kB
import { isSupported } from '../__internal__/is.svelte.js'; import { defaultWindow } from '../__internal__/configurable.js'; // Extracted from https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/entryType#value export const performanceEntryTypes = [ 'element', 'event', 'first-input', 'largest-contentful-paint', 'layout-shift', 'long-animation-frame', 'longtask', 'mark', 'measure', 'navigation', 'paint', 'resource', 'taskattribution', 'visibility-state' ]; /** * Observes performance metrics. * @param callback The callback for when performance entry events are recorded. * @param options Additional options to customize the behavior. * @see https://svelte-librarian.github.io/sv-use/docs/core/observe-performance */ export function observePerformance(callback, options) { const { window = defaultWindow, immediate = true, ...performanceOptions } = options; let _observer; const _isSupported = isSupported(() => window !== undefined && 'PerformanceObserver' in window); if (immediate) { resume(); } function resume() { if (!_isSupported.current) return; cleanup(); if (!_observer) { _observer = new PerformanceObserver(callback); } _observer.observe(performanceOptions); } function pause() { _observer?.disconnect(); } function cleanup() { _observer?.disconnect(); _observer = undefined; } return { get isSupported() { return _isSupported.current; }, resume, pause, cleanup }; }