release: WRNexusJS 0.7.0
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
export interface WebVitalsClientOptions {
|
||||
endpoint?: string;
|
||||
sampleRate?: number;
|
||||
}
|
||||
|
||||
export function webVitalsClient(options: WebVitalsClientOptions = {}): string {
|
||||
const endpoint = JSON.stringify(options.endpoint ?? "/__wrnexus/metrics/vitals");
|
||||
const sampleRate = Math.max(0, Math.min(1, options.sampleRate ?? 0.1));
|
||||
return `(function(){
|
||||
if (!window.PerformanceObserver || Math.random() > ${sampleRate}) return;
|
||||
var endpoint = ${endpoint};
|
||||
var cls = 0;
|
||||
function rating(name, value) {
|
||||
if (name === "LCP") return value <= 2500 ? "good" : value <= 4000 ? "needs-improvement" : "poor";
|
||||
if (name === "INP") return value <= 200 ? "good" : value <= 500 ? "needs-improvement" : "poor";
|
||||
if (name === "CLS") return value <= 0.1 ? "good" : value <= 0.25 ? "needs-improvement" : "poor";
|
||||
return "unknown";
|
||||
}
|
||||
function send(name, value) {
|
||||
var body = JSON.stringify({ name: name, value: value, rating: rating(name, value), route: location.pathname, navigationType: performance.getEntriesByType("navigation")[0]?.type });
|
||||
if (navigator.sendBeacon) navigator.sendBeacon(endpoint, new Blob([body], { type: "application/json" }));
|
||||
else fetch(endpoint, { method: "POST", headers: { "content-type": "application/json" }, body: body, keepalive: true }).catch(function(){});
|
||||
}
|
||||
try { new PerformanceObserver(function(list){ var entries=list.getEntries(); var last=entries[entries.length-1]; if(last) send("LCP", last.startTime); }).observe({type:"largest-contentful-paint",buffered:true}); } catch(_) {}
|
||||
try { new PerformanceObserver(function(list){ list.getEntries().forEach(function(e){ if(!e.hadRecentInput) cls += e.value; }); }).observe({type:"layout-shift",buffered:true}); } catch(_) {}
|
||||
try { new PerformanceObserver(function(list){ var max=0; list.getEntries().forEach(function(e){ max=Math.max(max,e.duration||0); }); if(max) send("INP",max); }).observe({type:"event",durationThreshold:40,buffered:true}); } catch(_) {}
|
||||
addEventListener("visibilitychange", function(){ if(document.visibilityState === "hidden" && cls) send("CLS", cls); }, { once: true });
|
||||
})();`;
|
||||
}
|
||||
Reference in New Issue
Block a user