web-vitals-reporter
Version:
Report Web Vitals to your API with one POST request per session
2 lines (1 loc) • 1.79 kB
JavaScript
function e(){return(e=Object.assign||function(e){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e}).apply(this,arguments)}function n(e,n){return void 0===n&&(n=0),+(Math.round(e+"e+"+n)+"e-"+n)}exports.createApiReporter=function(t,r){void 0===r&&(r={});var i=!1,o=!1,a=e({id:"v1-"+Date.now()+"-"+(Math.floor(8999999999999*Math.random())+1e12)},r.initial),u=function(){if(!i&&o){var u;if(a.duration=(u="undefined"==typeof performance?null:performance)&&u.now?n(u.now()):null,r.beforeSend){var c=r.beforeSend(a);c&&(a=e({},a,c))}if(i=!0,r.onSend)r.onSend(t,a);else{if("undefined"==typeof navigator)return;if(navigator.sendBeacon)return navigator.sendBeacon(t,JSON.stringify(a));var f=new XMLHttpRequest;f.open("POST",t,!1),f.setRequestHeader("Content-Type","text/plain;charset=UTF-8"),f.send(JSON.stringify(a))}}},c=r.mapMetric||function(e){var t,r=-1!==["FCP","TTFB","LCP","CLS","FID"].indexOf(e.name);return(t={})[e.name]=r?n(e.value,"CLS"===e.name?4:0):e.value,t};return setTimeout(function(){-1!==(PerformanceObserver&&PerformanceObserver.supportedEntryTypes||[]).indexOf("layout-shift")?addEventListener("visibilitychange",function e(){"hidden"===document.visibilityState&&(u(),removeEventListener("visibilitychange",e,!0))},!0):addEventListener("pagehide",u,{capture:!0,once:!0})}),function(n){o||(o=!0),a=e({},a,c(n,a))}},exports.getDeviceInfo=function(){var e="undefined"==typeof navigator?null:navigator,n=e&&e.connection?e.connection:null;return{url:location?location.href:null,referrer:document?document.referrer:null,userAgent:e?e.userAgent:null,memory:e?e.deviceMemory:void 0,cpus:e?e.hardwareConcurrency:void 0,connection:n?{effectiveType:n.effectiveType,rtt:n.rtt,downlink:n.downlink}:void 0}};