// snippets/Loading/Webfont-Usage-Analyzer.js | sha256:47176322809a830c | https://github.com/nucliweb/webperf-snippets/blob/main/snippets/Loading/Webfont-Usage-Analyzer.js (()=>{const e="Webfont-Usage-Analyzer",t=307200,s=/\.(woff2?|ttf|otf|eot)(\?|#|$)/i;if("undefined"==typeof FontFace||!document.fonts)return{script:e,status:"unsupported",message:"The CSS Font Loading API (document.fonts) is not available in this browser"};const n=e=>String(e).replace(/["']/g,"").trim(),o=e=>`${(e/1024).toFixed(1)} KB`;function a(e){const t=String(e).trim().toLowerCase();if("normal"===t)return[400,400];if("bold"===t)return[700,700];const s=t.split(/\s+/).map(Number).filter(e=>!Number.isNaN(e));return 0===s.length?[400,400]:[Math.min(...s),Math.max(...s)]}function r(e){const t=[];for(const s of String(e).split(",")){const e=s.trim().match(/^U\+([0-9a-f?]+)(?:-([0-9a-f]+))?$/i);if(e)if(e[1].includes("?"))t.push([parseInt(e[1].replace(/\?/g,"0"),16),parseInt(e[1].replace(/\?/g,"f"),16)]);else{const s=parseInt(e[1],16);t.push([s,e[2]?parseInt(e[2],16):s])}}return t}const i=e=>!e||/^U\+0-10FFFF$/i.test(e.trim()),l=e=>"normal"===String(e).trim().toLowerCase()?"normal":"slanted";let d=0;const u=new Map,c=(e,t,s,o)=>[n(e).toLowerCase(),String(t).trim()||"normal",String(s).trim()||"normal",i(o)?"":r(o).map(e=>e.join("-")).join(",")].join("|");function f(e,t,s){if(!(s>6))for(const n of e)if(n instanceof window.CSSFontFaceRule){const e=n.style,s=[...e.getPropertyValue("src").matchAll(/url\(\s*(["']?)(.*?)\1\s*\)/g)].map(e=>{try{return new URL(e[2],t).href}catch{return null}}).filter(e=>e&&!e.startsWith("data:")),o=c(e.getPropertyValue("font-family"),e.getPropertyValue("font-weight"),e.getPropertyValue("font-style"),e.getPropertyValue("unicode-range"));u.set(o,[...u.get(o)??[],s])}else n.styleSheet?g(n.styleSheet,s+1):n.cssRules&&f(n.cssRules,t,s+1)}function g(e,t){try{f(e.cssRules,e.href||location.href,t)}catch{d++}}Array.from(document.styleSheets).forEach(e=>g(e,0));const h=new Set([...u.values()].flat(2)),m=new Map;for(const e of performance.getEntriesByType("resource").filter(e=>!e.name.endsWith("#webperf-snippets")))(s.test(e.name)||h.has(e.name))&&m.set(e.name,Math.max(m.get(e.name)??0,e.encodedBodySize||0));const y=[...m.values()].reduce((e,t)=>e+t,0),p=[...m.values()].every(e=>e>0),w=new Map,b=new Set(["SCRIPT","STYLE","NOSCRIPT","TEMPLATE","HEAD","TITLE","META","LINK"]);function $(e,t,s){const o=s.replace(/\s+/g,"");if(!o)return;const a=`${t.fontFamily}|${t.fontWeight}|${t.fontStyle}`;let r=w.get(a);r||(r={families:[...t.fontFamily.matchAll(/"([^"]+)"|'([^']+)'|([^,]+)/g)].map(e=>n(e[1]??e[2]??e[3]).toLowerCase()),weight:Number(t.fontWeight)||400,style:t.fontStyle,codepoints:new Set},w.set(a,r));for(const e of o){if(r.codepoints.size>=2e4)break;r.codepoints.add(e.codePointAt(0))}}const S=e=>e&&"none"!==e&&"normal"!==e?e.replace(/^["']|["']$/g,"").replace(/\\([0-9a-f]{1,6})\s?/gi,(e,t)=>String.fromCodePoint(parseInt(t,16))).replace(/\\(.)/g,"$1"):"",v=[document.body,...document.body.querySelectorAll("*")],R=Math.min(v.length,2e4);for(let e=0;e{const t=n(e.family),s=i(e.unicodeRange)?"":e.unicodeRange.trim(),o=c(e.family,e.weight,e.style,e.unicodeRange),l=_.get(o)??0;_.set(o,l+1);const d=u.get(o)?.[l]??[],f=d.find(e=>m.has(e))??d[0]??"";return{family:t,weight:String(e.weight),style:String(e.style),display:e.display||"auto",unicodeRange:s,status:e.status,used:!1,bytes:"loaded"===e.status&&m.has(f)?m.get(f):0,url:f,_key:o,_redeclared:!1,_weightRange:a(e.weight),_ranges:s?r(s):null}}),M=(e,t)=>t>=e._weightRange[0]&&t<=e._weightRange[1]?0:Math.min(Math.abs(t-e._weightRange[0]),Math.abs(t-e._weightRange[1]));for(const e of w.values())for(const t of e.families){const s=C.filter(e=>e.family.toLowerCase()===t);if(0===s.length)continue;const n=s.filter(t=>l(t.style)===l(e.style)),o=(n.length?n:s).filter(t=>{return n=e.codepoints,!(s=t)._ranges||[...n].some(e=>((e,t)=>e.some(([e,s])=>t>=e&&t<=s))(s._ranges,e));var s,n});if(0===o.length)continue;const a=Math.min(...o.map(t=>M(t,e.weight)));o.filter(t=>M(t,e.weight)===a).forEach(e=>e.used=!0)}const F=new Map;C.forEach(e=>F.set(e._key,[...F.get(e._key)??[],e]));for(const e of F.values()){if(e.length<2)continue;const t=e.findLast(e=>"loaded"===e.status);t&&e.filter(e=>e!==t).forEach(e=>{e.used=!1,e._redeclared=!0})}const L=e=>e.length>60?`${e.slice(0,57)}...`:e,E=e=>`${e.family} ${e.weight} ${e.style}${e.unicodeRange?` (${L(e.unicodeRange)})`:""}`,T=C.filter(e=>"loaded"===e.status),A=T.filter(e=>!e.used),k=C.filter(e=>"unloaded"===e.status),N=C.filter(e=>"error"===e.status),P=k.filter(e=>e._redeclared),x=k.filter(e=>e.unicodeRange&&!e._redeclared),I=k.filter(e=>!e.unicodeRange&&!e._redeclared),V=C.filter(e=>!("loaded"!==e.status&&"loading"!==e.status||"auto"!==e.display&&"block"!==e.display)),O=new Set(T.filter(e=>e.used&&e.url).map(e=>e.url)),U=e=>e.url&&O.has(e.url)?0:e.bytes,W=[...new Map(A.map(e=>[e.url||E(e),U(e)])).values()].reduce((e,t)=>e+t,0),z=new Map;for(const e of C.filter(e=>e.unicodeRange)){const t=z.get(e.family)??{family:e.family,subsets:0,loadedSubsets:0};t.subsets++,"loaded"===e.status&&t.loadedSubsets++,z.set(e.family,t)}const B=[...z.values()].filter(e=>e.subsets>1).slice(0,20),D={};C.forEach(e=>D[e.display]=(D[e.display]??0)+1);const j=e=>[...new Set(e.map(E))],K=e=>{const t=j(e),s=t.slice(0,8).join(", ");return t.length>8?`${s} and ${t.length-8} more`:s},q=[...N.map(e=>({code:"load-failed",severity:"error",message:`Font failed to load: ${E(e)}`,target:e.url||E(e)})),...[...new Map(A.map(e=>[`${E(e)}|${e.url}`,e])).values()].map(e=>{const t=U(e)?`, ${o(U(e))} downloaded for nothing`:"",s=e.url||E(e);return e._redeclared?{code:"redeclared",severity:"warning",message:`Loaded but declared again later with the same descriptors, so the page renders with the other file: ${E(e)}${e.url?` from ${e.url}`:""}${t}`,target:s}:{code:"loaded-unused",severity:"warning",message:`Loaded but not used by any rendered element: ${E(e)}${t}`,target:s}})];V.length>0&&q.push({code:"blocking-font-display",severity:"warning",message:`font-display is auto or block on ${j(V).length} face(s), so text can stay invisible while they load. Use swap or optional: ${K(V)}`}),y>t&&q.push({code:"heavy-fonts",severity:"warning",message:`Web fonts weigh ${o(y)} in total (over ${o(t)}). Subset, use WOFF2 or drop unused weights`}),I.length>0&&q.push({code:"never-loaded",severity:"info",message:`Declared but never loaded (${j(I).length}); nothing on this page needed them: ${K(I)}`}),P.length>0&&q.push({code:"shadowed",severity:"info",message:`Declared more than once with the same descriptors; the page uses a later declaration, so these never loaded (${j(P).length}): ${K(P)}`}),x.length>0&&q.push({code:"unused-subsets",severity:"info",message:`unicode-range subsets this page did not need (${j(x).length}), which is the intended behavior of a split font: ${K(x)}`}),p||q.push({code:"size-unknown",severity:"info",message:"Some font files are cross-origin without Timing-Allow-Origin, so their size reads as 0 and the byte totals are a lower bound"}),d>0&&q.push({code:"unreadable-stylesheets",severity:"info",message:`${d} cross-origin stylesheet(s) could not be read, so their font files cannot be matched to faces`}),R"unloaded"!==e.status).forEach(e=>{const t=`${e._key}|${e.url}`;X.set(t,[...X.get(t)??[],e])});const Y=e=>e.used?"":"error"===e.status?"failed to load":"loaded"===e.status?e._redeclared?"declared again later":"loaded but not used":"",G=[...X.values()].map(e=>{const t=e.find(e=>e.used)??[...e].sort((e,t)=>H.indexOf(e.status)-H.indexOf(t.status))[0];return{...t,declarations:e.length,note:Y(t)}}),J=G.filter(e=>"loaded"===e.status),Q=j([...I,...x]);q.forEach(e=>{});const Z=e=>"error"===e.status?0:"loaded"!==e.status||e.used?"loaded"===e.status?2:3:1,ee=G.map((e,t)=>({f:e,index:t})).sort((e,t)=>Z(e.f)-Z(t.f)||e.index-t.index).slice(0,50).map(({f:e})=>({family:e.family,weight:e.weight,style:e.style,display:e.display,unicodeRange:L(e.unicodeRange),status:e.status,used:e.used,declarations:e.declarations,bytes:e.bytes,note:e.note,url:e.url}));return{script:e,status:"ok",count:G.length,corsLimitedAnalysis:!p,details:{declarationCount:C.length,loadedCount:J.length,usedCount:J.filter(e=>e.used).length,loadedUnusedCount:J.filter(e=>!e.used).length,loadedUnusedBytes:W,neverLoadedCount:Q.length,neverLoaded:Q.slice(0,50),errorCount:G.filter(e=>"error"===e.status).length,fontFileCount:m.size,totalFontBytes:y,bytesReadable:p,fontDisplay:D,unicodeRangeFamilies:B,unreadableStylesheets:d,elementsScanned:R},items:ee,issues:q}})();