// snippets/Loading/Script-Loading.js | sha256:c926cc2a1babbfd3 | https://github.com/nucliweb/webperf-snippets/blob/main/snippets/Loading/Script-Loading.js (()=>{const e=[];function t(e){if(null==e||Number.isNaN(e))return"-";if(0===e)return"0 B";const t=["B","KB","MB","GB"],r=Math.max(0,Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1));return(e/Math.pow(1024,r)).toFixed(1)+" "+t[r]}function r(e){const t=e.replace(/\.$/,"");if(/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||t.includes(":"))return t;const r=t.split(".");return r.length<=2?t:2===r[r.length-1].length&&["ac","co","com","edu","go","gob","gouv","gov","govt","mil","ne","net","nom","or","org","sch"].includes(r[r.length-2])?r.slice(-3).join("."):r.slice(-2).join(".")}const i=new Map;performance.getEntriesByType("resource").filter(e=>!e.name.endsWith("#webperf-snippets")).forEach(e=>{"script"===e.initiatorType&&i.set(e.name,{size:e.transferSize||0,sizeKnown:e.transferSize>0||e.encodedBodySize>0||e.decodedBodySize>0,duration:e.duration,startTime:e.startTime})});const n=Array.from(document.querySelectorAll("script[src]")),s=(Array.from(document.querySelectorAll("script:not([src])")).filter(e=>e.innerHTML.trim().length>0),n.map(t=>{const n=t.src,s=i.get(n)||{},o=null!==t.closest("head"),l="module"===t.type,a=t.async,c=t.defer,g=!0===t.noModule&&!l;let d="blocking";g?d="nomodule":l&&a?d="async module":l?d="module":a?d="async":c&&(d="defer");const h="blocking"===d,u=(t=>{try{return function(t){const i=r(t);return i===r(location.hostname)||e.some(e=>r(String(e).trim().toLowerCase().replace(/^[a-z]+:\/\//,"").split("/")[0])===i)}(new URL(t).hostname)}catch{return!0}})(n);return{src:n,shortSrc:n.split("/").pop()?.split("?")[0]||n,strategy:d,isBlocking:h,inHead:o,firstParty:u,isModule:l,isAsync:a,isDefer:c,size:s.size||0,sizeKnown:!!s.sizeKnown||g&&!i.has(n),duration:s.duration||0,startTime:s.startTime||0,element:t}})),o=s.filter(e=>e.isBlocking),l=o.filter(e=>e.inHead),a=s.filter(e=>"async"===e.strategy||"async module"===e.strategy),c=s.filter(e=>"defer"===e.strategy),g=s.filter(e=>"module"===e.strategy),d=s.filter(e=>"nomodule"===e.strategy),h=o.filter(e=>!e.firstParty),u=s.reduce((e,t)=>e+t.size,0);let y,m;o.reduce((e,t)=>e+t.size,0),0===l.length?(y="Good",m="#22c55e"):l.length<=2&&0===h.length?(y="Needs Review",m="#f59e0b"):(y="Needs Optimization",m="#ef4444"),s.length>0&&(s.sort((e,t)=>e.isBlocking!==t.isBlocking?e.isBlocking?-1:1:t.size-e.size).map(e=>{return{Script:e.shortSrc,Strategy:e.isBlocking?`🔴 ${e.strategy}`:e.strategy,Location:e.inHead?"head":"body",Party:e.firstParty?"1st":"3rd",Size:t(e.size),Duration:(r=e.duration,r>0?r.toFixed(0)+"ms":"-")};var r}),s.sort((e,t)=>e.startTime-t.startTime).forEach((e,t)=>{}));const f=[];l.length>0&&f.push({code:"blocking-in-head",severity:"error",message:`${l.length} blocking script(s) in `,scripts:l,fix:"Add 'defer' or 'async' attribute, or move to end of "}),h.length>0&&f.push({code:"third-party-blocking",severity:"error",message:`${h.length} third-party blocking script(s)`,scripts:h,fix:"Add 'async' for independent scripts, or load dynamically"});const p=o.filter(e=>e.size>51200);p.length>0&&f.push({code:"large-blocking",severity:"warning",message:`${p.length} large blocking script(s) (> 50 KB)`,scripts:p,fix:"Split code, use defer, or lazy load"});const z=o.filter(e=>{const t=Array.from(document.body.querySelectorAll("script[src]"));return t.indexOf(e.element)>=t.length-3});z.length>0&&o.length>z.length&&f.push({code:"could-defer",severity:"info",message:o.length-z.length+" blocking script(s) could potentially use defer",fix:"Test with defer attribute to improve parsing performance"}),f.length>0&&f.forEach(e=>{e.scripts&&e.scripts.forEach(e=>{})});const b=s.filter(e=>e.firstParty),k=s.filter(e=>!e.firstParty);if(k.length>0){const e=new Map;k.forEach(t=>{try{const r=new URL(t.src).hostname;e.has(r)||e.set(r,{count:0,size:0,blocking:0});const i=e.get(r);i.count++,i.size+=t.size,t.isBlocking&&i.blocking++}catch{}}),Array.from(e.entries()).sort((e,t)=>t[1].size-e[1].size).map(([e,r])=>({Host:e,Scripts:r.count,Size:t(r.size),Blocking:r.blocking>0?`⚠️ ${r.blocking}`:"0"}))}const w=0===l.length?"good":l.length<=2&&0===h.length?"needs-improvement":"poor",B=[...s].sort((e,t)=>Number(t.isBlocking)-Number(e.isBlocking)||Number(e.firstParty)-Number(t.firstParty)||t.size-e.size);return{script:"Script-Loading",status:"ok",count:s.length,corsLimitedAnalysis:s.some(e=>!e.sizeKnown),rating:w,details:{totalSizeBytes:u,sizeUnknownCount:s.filter(e=>!e.sizeKnown).length,byStrategy:{blocking:o.length,async:a.length,defer:c.length,module:g.length,nomodule:d.length},byParty:{firstParty:b.length,thirdParty:k.length},thirdPartyBlockingCount:h.length},items:B.slice(0,50).map(e=>({url:e.src,shortName:e.shortSrc,strategy:e.strategy,location:e.inHead?"head":"body",party:e.firstParty?"first":"third",sizeBytes:e.size,sizeKnown:e.sizeKnown,durationMs:Math.round(e.duration)})),issues:[...f.map(e=>({code:e.code,severity:e.severity,message:e.message})),...s.some(e=>!e.sizeKnown)?[{code:"unknown-size",severity:"info",message:`${s.filter(e=>!e.sizeKnown).length} script(s) have an unknown size (missing Timing-Allow-Origin); total size is a lower bound`}]:[]]}})();