// snippets/CoreWebVitals/LCP-Image-Entropy.js | sha256:735dc092285d4598 | https://github.com/nucliweb/webperf-snippets/blob/main/snippets/CoreWebVitals/LCP-Image-Entropy.js
(async()=>{if(!PerformanceObserver.supportedEntryTypes?.includes("largest-contentful-paint"))return{script:"LCP-Image-Entropy",status:"unsupported",error:"largest-contentful-paint entries not supported in this browser"};function e(e){if(null==e||Number.isNaN(e))return"-";if(0===e)return"0 B";const t=["B","KB","MB","GB"],i=Math.max(0,Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1));return(e/Math.pow(1024,i)).toFixed(1)+" "+t[i]}function t(e,t){const i=function(e){const t=e.getBoundingClientRect(),i=getComputedStyle(e),r=e=>parseFloat(i[e])||0;return{width:Math.max(0,t.width-r("borderLeftWidth")-r("borderRightWidth")-r("paddingLeft")-r("paddingRight")),height:Math.max(0,t.height-r("borderTopWidth")-r("borderBottomWidth")-r("paddingTop")-r("paddingBottom"))}}(e),r=Math.min(i.width*i.height,e.naturalWidth*e.naturalHeight);return{displayed:i,bpp:r>0?8*t/r:0}}let i=null,r=null;const n=new PerformanceObserver(e=>{const t=e.getEntries(),n=t[t.length-1];n&&(i=n.element,r=n.url)});n.observe({type:"largest-contentful-paint",buffered:!0}),setTimeout(()=>{n.disconnect();const o=[...document.images].filter(e=>{const t=e.currentSrc||e.src;return t&&!t.startsWith("data:image")}).map(e=>{const n=e.currentSrc||e.src,o=performance.getEntriesByName(n)[0],s=o?.encodedBodySize||0,{displayed:a,bpp:p}=t(e,s),l=p>0&&p<.05,d=i===e||r===n;return{element:e,src:n,shortSrc:n.split("/").pop()?.split("?")[0]||n,width:e.naturalWidth,height:e.naturalHeight,displayedWidth:Math.round(a.width),displayedHeight:Math.round(a.height),fileSize:s,bpp:p,isLowEntropy:l,isLCP:d,lcpEligible:!l&&p>0}}).filter(e=>e.bpp>0);if(0===o.length)return;const s=o.filter(e=>e.isLowEntropy);o.filter(e=>!e.isLowEntropy),o.find(e=>e.isLCP);o.sort((e,t)=>t.bpp-e.bpp).map(t=>({Image:t.shortSrc.length>30?"..."+t.shortSrc.slice(-27):t.shortSrc,Dimensions:`${t.width}×${t.height}`,Displayed:`${t.displayedWidth}×${t.displayedHeight}`,Size:e(t.fileSize),BPP:t.bpp.toFixed(4),Entropy:t.isLowEntropy?"🔴 Low":"🟢 Normal","LCP Eligible":t.lcpEligible?"✅":"❌","Is LCP":t.isLCP?"👈":""})),s.length>0&&s.forEach(e=>{}),o.forEach((e,t)=>{})},100);const o=(await new Promise(e=>{const t=[],i=new PerformanceObserver(e=>t.push(...e.getEntries()));i.observe({type:"largest-contentful-paint",buffered:!0}),setTimeout(()=>{i.disconnect(),e(t)},100)})).at(-1),s=o?.element??null,a=o?.url??null,p=[...document.images].filter(e=>{const t=e.currentSrc||e.src;return t&&!t.startsWith("data:image")}).map(e=>{const i=e.currentSrc||e.src,r=performance.getEntriesByName(i)[0],n=r?.encodedBodySize||0,{displayed:o,bpp:p}=t(e,n),l=p>0&&p<.05,d=s===e||a===i;return{url:i.split("/").pop()?.split("?")[0]||i,width:e.naturalWidth,height:e.naturalHeight,displayedWidth:Math.round(o.width),displayedHeight:Math.round(o.height),fileSizeBytes:n,bpp:Math.round(1e4*p)/1e4,isLowEntropy:l,lcpEligible:!l&&p>0,isLCP:d}}).filter(e=>e.bpp>0),l=p.filter(e=>e.isLowEntropy).length,d=p.find(e=>e.isLCP);s&&(s.style.outline="3px dashed lime",s.style.outlineOffset="2px");const h=[];l>0&&h.push({code:"low-entropy-images",severity:"warning",message:`${l} image(s) have low entropy and are LCP-ineligible in Chrome 112+`}),d?.isLowEntropy&&h.push({code:"lcp-low-entropy",severity:"error",message:"Current LCP image has low entropy and may be skipped by Chrome"});const u=s?s.tagName.toLowerCase():null;u&&!d&&h.push("img"===u?{code:"lcp-size-unknown",severity:"info",message:"The LCP
has no file size to read, as with a data: URL or a cross-origin image without Timing-Allow-Origin, so its entropy cannot be computed."}:a?{code:"lcp-not-img",severity:"info",message:`The LCP is the image of a <${u}>, such as a CSS background or a video poster, and this snippet reads
elements only. Run the LCP snippet to measure it.`}:{code:"lcp-is-text",severity:"info",message:`The LCP element is <${u}>, text and not an image, so its entropy does not apply. Run the LCP snippet to measure it.`});const c=[...p].sort((e,t)=>Number(t.isLCP)-Number(e.isLCP)||Number(t.isLowEntropy)-Number(e.isLowEntropy)||e.bpp-t.bpp);return{script:"LCP-Image-Entropy",status:"ok",count:p.length,details:{totalImages:p.length,lowEntropyCount:l,lcpElement:u,lcpImageEligible:d?!d.isLowEntropy:null,lcpImage:d?{url:d.url,bpp:d.bpp,isLowEntropy:d.isLowEntropy}:null},items:c.slice(0,50),issues:h}})();