From 7150c171cd845d9ea8d21e3a44c2b7f6b58855fa Mon Sep 17 00:00:00 2001 From: WordPress Fan <146129302+wordpressfan@users.noreply.github.com> Date: Fri, 30 Aug 2024 15:58:48 +0300 Subject: [PATCH] Depend on php to identify elements and depth (PR #6929) Co-authored-by: Mai <76941962+Mai-Saad@users.noreply.github.com> --- assets/js/wpr-beacon.js | 16 +++---- assets/js/wpr-beacon.min.js | 2 +- assets/js/wpr-beacon.min.js.map | 6 +-- .../LazyRenderContent/Frontend/Controller.php | 19 -------- .../Frontend/Processor/Dom.php | 16 +++---- .../Frontend/Processor/HelperTrait.php | 47 +++++++++++++++++++ .../Frontend/Processor/Regex.php | 16 +++---- .../Frontend/Processor/SimpleHtmlDom.php | 16 +++---- package.json | 2 +- .../Subscriber/HTML/output_w_beacon.html | 2 +- .../HTML/output_with_beacon_and_atf_opt.html | 2 +- .../output_with_beacon_and_only_lrc_opt.html | 2 +- .../Frontend/Controller/addCustomData.php | 2 - 13 files changed, 79 insertions(+), 69 deletions(-) create mode 100644 inc/Engine/Optimization/LazyRenderContent/Frontend/Processor/HelperTrait.php diff --git a/assets/js/wpr-beacon.js b/assets/js/wpr-beacon.js index 94d3d21198..1275eb3f64 100644 --- a/assets/js/wpr-beacon.js +++ b/assets/js/wpr-beacon.js @@ -209,7 +209,7 @@ } } _getLazyRenderElements() { - const elements = document.querySelectorAll(this.config.lrc_elements); + const elements = document.querySelectorAll("[data-rocket-location-hash]"); if (elements.length <= 0) { return []; } @@ -233,7 +233,7 @@ _getElementDistance(element) { const rect = element.getBoundingClientRect(); const scrollTop = window.pageYOffset || document.documentElement.scrollTop; - return Math.max(0, rect.top + scrollTop - (window.innerHeight || document.documentElement.clientHeight)); + return Math.max(0, rect.top + scrollTop); } _skipElement(element) { const skipStrings = this.config.skipStrings || ["memex"]; @@ -259,18 +259,14 @@ if ("No hash detected" === hash) { return; } - const color = depth === 2 && distance >= this.config.lrc_threshold || element.parentElement && this._getElementDistance(element.parentElement) === 0 && distance >= this.config.lrc_threshold ? "green" : distance === 0 ? "red" : ""; + const can_push_hash = element.parentElement && this._getElementDistance(element.parentElement) < this.config.lrc_threshold && distance > this.config.lrc_threshold; + const color = can_push_hash ? "green" : distance === 0 ? "red" : ""; this.logger.logColoredMessage(`${" ".repeat(depth)}${element.tagName} (Depth: ${depth}, Distance from viewport top: ${distance}px)`, color); this.logger.logColoredMessage(`${" ".repeat(depth)}Location hash: ${hash}`, color); this.logger.logColoredMessage(`${" ".repeat(depth)}Dimensions Client Height: ${element.clientHeight}`, color); - if (depth === 2 && distance >= this.config.lrc_threshold) { + if (can_push_hash) { this.lazyRenderElements.push(hash); - this.logger.logMessage(`Parent element at depth 2 with distance >= this.config.lrc_threshold pushed with hash: ${hash}`); - return; - } - if (element.parentElement && this._getElementDistance(element.parentElement) === 0 && distance >= this.config.lrc_threshold) { - this.lazyRenderElements.push(hash); - this.logger.logMessage(`Child element pushed with hash: ${hash}`); + this.logger.logMessage(`Element pushed with hash: ${hash}`); } }); } diff --git a/assets/js/wpr-beacon.min.js b/assets/js/wpr-beacon.min.js index abfac1251e..fba30fa208 100644 --- a/assets/js/wpr-beacon.min.js +++ b/assets/js/wpr-beacon.min.js @@ -1,2 +1,2 @@ -(()=>{var h=class{static isNotValidScreensize(e,i){const t=window.innerWidth||document.documentElement.clientWidth,r=window.innerHeight||document.documentElement.clientHeight,n=e&&(t>i.width||r>i.height),s=!e&&(t=0&&e.right>=0&&e.top<=(window.innerHeight||document.documentElement.clientHeight)&&e.left<=(window.innerWidth||document.documentElement.clientWidth)}},c=h,u=class{constructor(e,i){this.config=e,this.performanceImages=[],this.logger=i}async run(){try{const e=this._generateLcpCandidates(1/0);e&&(this._initWithFirstElementWithInfo(e),this._fillATFWithoutDuplications(e))}catch(e){this.errorCode="script_error",this.logger.logMessage("Script Error: "+e)}}_generateLcpCandidates(e){const i=document.querySelectorAll(this.config.elements);return i.length<=0?[]:Array.from(i).map(n=>{if(n.nodeName.toLowerCase()==="img"&&n.parentElement.nodeName.toLowerCase()==="picture")return null;let s;if(n.nodeName.toLowerCase()==="picture"){const a=n.querySelector("img");if(a)s=a.getBoundingClientRect();else return null}else s=n.getBoundingClientRect();return{element:n,rect:s}}).filter(n=>n!==null).filter(n=>n.rect.width>0&&n.rect.height>0&&c.isIntersecting(n.rect)).map(n=>({item:n,area:this._getElementArea(n.rect),elementInfo:this._getElementInfo(n.element)})).sort((n,s)=>s.area-n.area).slice(0,e).map(n=>({element:n.item.element,elementInfo:n.elementInfo}))}_getElementArea(e){const i=Math.min(e.width,(window.innerWidth||document.documentElement.clientWidth)-e.left),t=Math.min(e.height,(window.innerHeight||document.documentElement.clientHeight)-e.top);return i*t}_getElementInfo(e){const i=e.nodeName.toLowerCase(),t={type:"",src:"",srcset:"",sizes:"",sources:[],bg_set:[],current_src:""},r=/url\(\s*?['"]?\s*?(.+?)\s*?["']?\s*?\)/ig;if(i==="img"&&e.srcset)t.type="img-srcset",t.src=e.src,t.srcset=e.srcset,t.sizes=e.sizes,t.current_src=e.currentSrc;else if(i==="img")t.type="img",t.src=e.src,t.current_src=e.currentSrc;else if(i==="video"){t.type="img";const n=e.querySelector("source");t.src=e.poster||(n?n.src:""),t.current_src=t.src}else if(i==="svg"){const n=e.querySelector("image");n&&(t.type="img",t.src=n.getAttribute("href")||"",t.current_src=t.src)}else if(i==="picture"){t.type="picture";const n=e.querySelector("img");t.src=n?n.src:"",t.sources=Array.from(e.querySelectorAll("source")).map(s=>({srcset:s.srcset||"",media:s.media||"",type:s.type||"",sizes:s.sizes||""}))}else{const s=[window.getComputedStyle(e,null).getPropertyValue("background-image"),getComputedStyle(e,":after").getPropertyValue("background-image"),getComputedStyle(e,":before").getPropertyValue("background-image")].filter(o=>o!=="none");if(s.length===0)return null;const a=s[0];if(t.type="bg-img",a.includes("image-set(")&&(t.type="bg-img-set"),!a||a===""||a.includes("data:image"))return null;const g=[...a.matchAll(r)];t.bg_set=g.map(o=>o[1]?{src:o[1].trim()+(o[2]?" "+o[2].trim():"")}:{}),t.bg_set.every(o=>o.src==="")&&(t.bg_set=g.map(o=>o[1]?{src:o[1].trim()}:{})),t.bg_set.length>0&&(t.src=t.bg_set[0].src,t.type==="bg-img-set"&&(t.src=t.bg_set))}return t}_initWithFirstElementWithInfo(e){const i=e.find(t=>t.elementInfo!==null);if(!i){this.logger.logMessage("No LCP candidate found."),this.performanceImages=[];return}this.performanceImages=[{...i.elementInfo,label:"lcp"}]}_fillATFWithoutDuplications(e){e.forEach(({element:i,elementInfo:t})=>{this._isDuplicateImage(i)||!t||this.performanceImages.push({...t,label:"above-the-fold"})})}_isDuplicateImage(e){const i=this._getElementInfo(e);if(i===null)return!1;const t=i.type==="img"||i.type==="img-srcset"||i.type==="video",r=i.type==="bg-img"||i.type==="bg-img-set"||i.type==="picture";return(t||r)&&this.performanceImages.some(n=>n.src===i.src)}getResults(){return this.performanceImages}},d=u,m=class{constructor(e,i){this.config=e,this.logger=i,this.lazyRenderElements=[]}async run(){try{const e=this._getLazyRenderElements();e&&this._processElements(e)}catch(e){this.errorCode="script_error",this.logger.logMessage("Script Error: "+e)}}_getLazyRenderElements(){const e=document.querySelectorAll(this.config.lrc_elements);return e.length<=0?[]:Array.from(e).filter(t=>!this._skipElement(t)).map(t=>({element:t,depth:this._getElementDepth(t),distance:this._getElementDistance(t),hash:this._getLocationHash(t)}))}_getElementDepth(e){let i=0,t=e.parentElement;for(;t;)i++,t=t.parentElement;return i}_getElementDistance(e){const i=e.getBoundingClientRect(),t=window.pageYOffset||document.documentElement.scrollTop;return Math.max(0,i.top+t-(window.innerHeight||document.documentElement.clientHeight))}_skipElement(e){const i=this.config.skipStrings||["memex"];return!e||!e.id?!1:i.some(t=>e.id.toLowerCase().includes(t))}_shouldSkipElement(e,i){if(!e)return!1;for(let t=0;t{if(this._shouldSkipElement(i,this.config.exclusions||[])||n==="No hash detected")return;const s=t===2&&r>=this.config.lrc_threshold||i.parentElement&&this._getElementDistance(i.parentElement)===0&&r>=this.config.lrc_threshold?"green":r===0?"red":"";if(this.logger.logColoredMessage(`${" ".repeat(t)}${i.tagName} (Depth: ${t}, Distance from viewport top: ${r}px)`,s),this.logger.logColoredMessage(`${" ".repeat(t)}Location hash: ${n}`,s),this.logger.logColoredMessage(`${" ".repeat(t)}Dimensions Client Height: ${i.clientHeight}`,s),t===2&&r>=this.config.lrc_threshold){this.lazyRenderElements.push(n),this.logger.logMessage(`Parent element at depth 2 with distance >= this.config.lrc_threshold pushed with hash: ${n}`);return}i.parentElement&&this._getElementDistance(i.parentElement)===0&&r>=this.config.lrc_threshold&&(this.lazyRenderElements.push(n),this.logger.logMessage(`Child element pushed with hash: ${n}`))})}_getXPath(e){return e.id!==""?`//*[@id="${e.id}"]`:this._getElementXPath(e)}_getElementXPath(e){if(e===document.body)return"/html/body";const i=this._getElementPosition(e);return`${this._getElementXPath(e.parentNode)}/${e.nodeName.toLowerCase()}[${i}]`}_getElementPosition(e){let i=1,t=e.previousElementSibling;for(;t;)t.nodeName===e.nodeName&&i++,t=t.previousElementSibling;return i}_getLocationHash(e){return e.hasAttribute("data-rocket-location-hash")?e.getAttribute("data-rocket-location-hash"):"No hash detected"}getResults(){return this.lazyRenderElements}},p=m,f=class{constructor(e){this.enabled=e}logMessage(e){this.enabled&&console.log(e)}logColoredMessage(e,i="green"){this.enabled&&console.log(`%c${e}`,`color: ${i};`)}},_=f,b=class{constructor(e){this.config=e,this.lcpBeacon=null,this.lrcBeacon=null,this.infiniteLoopId=null,this.errorCode="",this.logger=new _(this.config.debug)}async init(){if(this.scriptTimer=new Date,!await this._isValidPreconditions()){this._finalize();return}this.infiniteLoopId=setTimeout(()=>{this._handleInfiniteLoop()},1e4);const e=await this._getGeneratedBefore(),i=this.config.status.atf&&(e===!1||e.lcp===!1),t=this.config.status.lrc&&(e===!1||e.lrc===!1);i?(this.lcpBeacon=new d(this.config,this.logger),await this.lcpBeacon.run()):this.logger.logMessage("Not running BeaconLcp because data is already available or feature is disabled"),t?(this.lrcBeacon=new p(this.config,this.logger),await this.lrcBeacon.run()):this.logger.logMessage("Not running BeaconLrc because data is already available or feature is disabled"),i||t?this._saveFinalResultIntoDB():(this.logger.logMessage("Not saving results into DB as no beacon features ran."),this._finalize())}async _isValidPreconditions(){const e={width:this.config.width_threshold,height:this.config.height_threshold};return c.isNotValidScreensize(this.config.is_mobile,e)?(this.logger.logMessage("Bailing out because screen size is not acceptable"),!1):!0}async _getGeneratedBefore(){if(!c.isPageCached())return!1;let e=new FormData;return e.append("action","rocket_check_beacon"),e.append("rocket_beacon_nonce",this.config.nonce),e.append("url",this.config.url),e.append("is_mobile",this.config.is_mobile),(await fetch(this.config.ajax_url,{method:"POST",credentials:"same-origin",body:e}).then(t=>t.json())).data}_saveFinalResultIntoDB(){const e={lcp:this.lcpBeacon?this.lcpBeacon.getResults():null,lrc:this.lrcBeacon?this.lrcBeacon.getResults():null},i=new FormData;i.append("action","rocket_beacon"),i.append("rocket_beacon_nonce",this.config.nonce),i.append("url",this.config.url),i.append("is_mobile",this.config.is_mobile),i.append("status",this._getFinalStatus()),i.append("results",JSON.stringify(e)),fetch(this.config.ajax_url,{method:"POST",credentials:"same-origin",body:i,headers:{"wpr-saas-no-intercept":!0}}).then(t=>t.json()).then(t=>{this.logger.logMessage(t.data.lcp)}).catch(t=>{this.logger.logMessage(t)}).finally(()=>{this._finalize()})}_getFinalStatus(){return this.errorCode!==""?this.errorCode:10<=(new Date-this.scriptTimer)/1e3?"timeout":"success"}_handleInfiniteLoop(){this._saveFinalResultIntoDB()}_finalize(){document.querySelector('[data-name="wpr-wpr-beacon"]').setAttribute("beacon-completed","true"),clearTimeout(this.infiniteLoopId)}},l=b;(e=>{if(!e)return;const i=new l(e);if(document.readyState!=="loading"){setTimeout(()=>{i.init()},e.delay);return}document.addEventListener("DOMContentLoaded",()=>{setTimeout(()=>{i.init()},e.delay)})})(window.rocket_beacon_data);var y=l})(); +(()=>{var h=class{static isNotValidScreensize(e,i){const t=window.innerWidth||document.documentElement.clientWidth,r=window.innerHeight||document.documentElement.clientHeight,s=e&&(t>i.width||r>i.height),n=!e&&(t=0&&e.right>=0&&e.top<=(window.innerHeight||document.documentElement.clientHeight)&&e.left<=(window.innerWidth||document.documentElement.clientWidth)}},c=h,u=class{constructor(e,i){this.config=e,this.performanceImages=[],this.logger=i}async run(){try{const e=this._generateLcpCandidates(1/0);e&&(this._initWithFirstElementWithInfo(e),this._fillATFWithoutDuplications(e))}catch(e){this.errorCode="script_error",this.logger.logMessage("Script Error: "+e)}}_generateLcpCandidates(e){const i=document.querySelectorAll(this.config.elements);return i.length<=0?[]:Array.from(i).map(s=>{if(s.nodeName.toLowerCase()==="img"&&s.parentElement.nodeName.toLowerCase()==="picture")return null;let n;if(s.nodeName.toLowerCase()==="picture"){const o=s.querySelector("img");if(o)n=o.getBoundingClientRect();else return null}else n=s.getBoundingClientRect();return{element:s,rect:n}}).filter(s=>s!==null).filter(s=>s.rect.width>0&&s.rect.height>0&&c.isIntersecting(s.rect)).map(s=>({item:s,area:this._getElementArea(s.rect),elementInfo:this._getElementInfo(s.element)})).sort((s,n)=>n.area-s.area).slice(0,e).map(s=>({element:s.item.element,elementInfo:s.elementInfo}))}_getElementArea(e){const i=Math.min(e.width,(window.innerWidth||document.documentElement.clientWidth)-e.left),t=Math.min(e.height,(window.innerHeight||document.documentElement.clientHeight)-e.top);return i*t}_getElementInfo(e){const i=e.nodeName.toLowerCase(),t={type:"",src:"",srcset:"",sizes:"",sources:[],bg_set:[],current_src:""},r=/url\(\s*?['"]?\s*?(.+?)\s*?["']?\s*?\)/ig;if(i==="img"&&e.srcset)t.type="img-srcset",t.src=e.src,t.srcset=e.srcset,t.sizes=e.sizes,t.current_src=e.currentSrc;else if(i==="img")t.type="img",t.src=e.src,t.current_src=e.currentSrc;else if(i==="video"){t.type="img";const s=e.querySelector("source");t.src=e.poster||(s?s.src:""),t.current_src=t.src}else if(i==="svg"){const s=e.querySelector("image");s&&(t.type="img",t.src=s.getAttribute("href")||"",t.current_src=t.src)}else if(i==="picture"){t.type="picture";const s=e.querySelector("img");t.src=s?s.src:"",t.sources=Array.from(e.querySelectorAll("source")).map(n=>({srcset:n.srcset||"",media:n.media||"",type:n.type||"",sizes:n.sizes||""}))}else{const n=[window.getComputedStyle(e,null).getPropertyValue("background-image"),getComputedStyle(e,":after").getPropertyValue("background-image"),getComputedStyle(e,":before").getPropertyValue("background-image")].filter(a=>a!=="none");if(n.length===0)return null;const o=n[0];if(t.type="bg-img",o.includes("image-set(")&&(t.type="bg-img-set"),!o||o===""||o.includes("data:image"))return null;const g=[...o.matchAll(r)];t.bg_set=g.map(a=>a[1]?{src:a[1].trim()+(a[2]?" "+a[2].trim():"")}:{}),t.bg_set.every(a=>a.src==="")&&(t.bg_set=g.map(a=>a[1]?{src:a[1].trim()}:{})),t.bg_set.length>0&&(t.src=t.bg_set[0].src,t.type==="bg-img-set"&&(t.src=t.bg_set))}return t}_initWithFirstElementWithInfo(e){const i=e.find(t=>t.elementInfo!==null);if(!i){this.logger.logMessage("No LCP candidate found."),this.performanceImages=[];return}this.performanceImages=[{...i.elementInfo,label:"lcp"}]}_fillATFWithoutDuplications(e){e.forEach(({element:i,elementInfo:t})=>{this._isDuplicateImage(i)||!t||this.performanceImages.push({...t,label:"above-the-fold"})})}_isDuplicateImage(e){const i=this._getElementInfo(e);if(i===null)return!1;const t=i.type==="img"||i.type==="img-srcset"||i.type==="video",r=i.type==="bg-img"||i.type==="bg-img-set"||i.type==="picture";return(t||r)&&this.performanceImages.some(s=>s.src===i.src)}getResults(){return this.performanceImages}},d=u,p=class{constructor(e,i){this.config=e,this.logger=i,this.lazyRenderElements=[]}async run(){try{const e=this._getLazyRenderElements();e&&this._processElements(e)}catch(e){this.errorCode="script_error",this.logger.logMessage("Script Error: "+e)}}_getLazyRenderElements(){const e=document.querySelectorAll("[data-rocket-location-hash]");return e.length<=0?[]:Array.from(e).filter(t=>!this._skipElement(t)).map(t=>({element:t,depth:this._getElementDepth(t),distance:this._getElementDistance(t),hash:this._getLocationHash(t)}))}_getElementDepth(e){let i=0,t=e.parentElement;for(;t;)i++,t=t.parentElement;return i}_getElementDistance(e){const i=e.getBoundingClientRect(),t=window.pageYOffset||document.documentElement.scrollTop;return Math.max(0,i.top+t)}_skipElement(e){const i=this.config.skipStrings||["memex"];return!e||!e.id?!1:i.some(t=>e.id.toLowerCase().includes(t))}_shouldSkipElement(e,i){if(!e)return!1;for(let t=0;t{if(this._shouldSkipElement(i,this.config.exclusions||[])||s==="No hash detected")return;const n=i.parentElement&&this._getElementDistance(i.parentElement)this.config.lrc_threshold,o=n?"green":r===0?"red":"";this.logger.logColoredMessage(`${" ".repeat(t)}${i.tagName} (Depth: ${t}, Distance from viewport top: ${r}px)`,o),this.logger.logColoredMessage(`${" ".repeat(t)}Location hash: ${s}`,o),this.logger.logColoredMessage(`${" ".repeat(t)}Dimensions Client Height: ${i.clientHeight}`,o),n&&(this.lazyRenderElements.push(s),this.logger.logMessage(`Element pushed with hash: ${s}`))})}_getXPath(e){return e.id!==""?`//*[@id="${e.id}"]`:this._getElementXPath(e)}_getElementXPath(e){if(e===document.body)return"/html/body";const i=this._getElementPosition(e);return`${this._getElementXPath(e.parentNode)}/${e.nodeName.toLowerCase()}[${i}]`}_getElementPosition(e){let i=1,t=e.previousElementSibling;for(;t;)t.nodeName===e.nodeName&&i++,t=t.previousElementSibling;return i}_getLocationHash(e){return e.hasAttribute("data-rocket-location-hash")?e.getAttribute("data-rocket-location-hash"):"No hash detected"}getResults(){return this.lazyRenderElements}},m=p,f=class{constructor(e){this.enabled=e}logMessage(e){this.enabled&&console.log(e)}logColoredMessage(e,i="green"){this.enabled&&console.log(`%c${e}`,`color: ${i};`)}},_=f,b=class{constructor(e){this.config=e,this.lcpBeacon=null,this.lrcBeacon=null,this.infiniteLoopId=null,this.errorCode="",this.logger=new _(this.config.debug)}async init(){if(this.scriptTimer=new Date,!await this._isValidPreconditions()){this._finalize();return}this.infiniteLoopId=setTimeout(()=>{this._handleInfiniteLoop()},1e4);const e=await this._getGeneratedBefore(),i=this.config.status.atf&&(e===!1||e.lcp===!1),t=this.config.status.lrc&&(e===!1||e.lrc===!1);i?(this.lcpBeacon=new d(this.config,this.logger),await this.lcpBeacon.run()):this.logger.logMessage("Not running BeaconLcp because data is already available or feature is disabled"),t?(this.lrcBeacon=new m(this.config,this.logger),await this.lrcBeacon.run()):this.logger.logMessage("Not running BeaconLrc because data is already available or feature is disabled"),i||t?this._saveFinalResultIntoDB():(this.logger.logMessage("Not saving results into DB as no beacon features ran."),this._finalize())}async _isValidPreconditions(){const e={width:this.config.width_threshold,height:this.config.height_threshold};return c.isNotValidScreensize(this.config.is_mobile,e)?(this.logger.logMessage("Bailing out because screen size is not acceptable"),!1):!0}async _getGeneratedBefore(){if(!c.isPageCached())return!1;let e=new FormData;return e.append("action","rocket_check_beacon"),e.append("rocket_beacon_nonce",this.config.nonce),e.append("url",this.config.url),e.append("is_mobile",this.config.is_mobile),(await fetch(this.config.ajax_url,{method:"POST",credentials:"same-origin",body:e}).then(t=>t.json())).data}_saveFinalResultIntoDB(){const e={lcp:this.lcpBeacon?this.lcpBeacon.getResults():null,lrc:this.lrcBeacon?this.lrcBeacon.getResults():null},i=new FormData;i.append("action","rocket_beacon"),i.append("rocket_beacon_nonce",this.config.nonce),i.append("url",this.config.url),i.append("is_mobile",this.config.is_mobile),i.append("status",this._getFinalStatus()),i.append("results",JSON.stringify(e)),fetch(this.config.ajax_url,{method:"POST",credentials:"same-origin",body:i,headers:{"wpr-saas-no-intercept":!0}}).then(t=>t.json()).then(t=>{this.logger.logMessage(t.data.lcp)}).catch(t=>{this.logger.logMessage(t)}).finally(()=>{this._finalize()})}_getFinalStatus(){return this.errorCode!==""?this.errorCode:10<=(new Date-this.scriptTimer)/1e3?"timeout":"success"}_handleInfiniteLoop(){this._saveFinalResultIntoDB()}_finalize(){document.querySelector('[data-name="wpr-wpr-beacon"]').setAttribute("beacon-completed","true"),clearTimeout(this.infiniteLoopId)}},l=b;(e=>{if(!e)return;const i=new l(e);if(document.readyState!=="loading"){setTimeout(()=>{i.init()},e.delay);return}document.addEventListener("DOMContentLoaded",()=>{setTimeout(()=>{i.init()},e.delay)})})(window.rocket_beacon_data);var y=l})(); //# sourceMappingURL=wpr-beacon.min.js.map diff --git a/assets/js/wpr-beacon.min.js.map b/assets/js/wpr-beacon.min.js.map index 2972a939f5..2c6e4c273c 100644 --- a/assets/js/wpr-beacon.min.js.map +++ b/assets/js/wpr-beacon.min.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["wpr-beacon.js"], - "sourcesContent": ["(() => {\n // src/Utils.js\n var BeaconUtils = class {\n static isNotValidScreensize(is_mobile, threshold) {\n const screenWidth = window.innerWidth || document.documentElement.clientWidth;\n const screenHeight = window.innerHeight || document.documentElement.clientHeight;\n const isNotValidForMobile = is_mobile && (screenWidth > threshold.width || screenHeight > threshold.height);\n const isNotValidForDesktop = !is_mobile && (screenWidth < threshold.width || screenHeight < threshold.height);\n return isNotValidForMobile || isNotValidForDesktop;\n }\n static isPageCached() {\n const signature = document.documentElement.nextSibling && document.documentElement.nextSibling.data ? document.documentElement.nextSibling.data : \"\";\n return signature && signature.includes(\"Debug: cached\");\n }\n static isIntersecting(rect) {\n return rect.bottom >= 0 && rect.right >= 0 && rect.top <= (window.innerHeight || document.documentElement.clientHeight) && rect.left <= (window.innerWidth || document.documentElement.clientWidth);\n }\n };\n var Utils_default = BeaconUtils;\n\n // src/BeaconLcp.js\n var BeaconLcp = class {\n constructor(config, logger) {\n this.config = config;\n this.performanceImages = [];\n this.logger = logger;\n }\n async run() {\n try {\n const above_the_fold_images = this._generateLcpCandidates(Infinity);\n if (above_the_fold_images) {\n this._initWithFirstElementWithInfo(above_the_fold_images);\n this._fillATFWithoutDuplications(above_the_fold_images);\n }\n } catch (err) {\n this.errorCode = \"script_error\";\n this.logger.logMessage(\"Script Error: \" + err);\n }\n }\n _generateLcpCandidates(count) {\n const lcpElements = document.querySelectorAll(this.config.elements);\n if (lcpElements.length <= 0) {\n return [];\n }\n const potentialCandidates = Array.from(lcpElements);\n const topCandidates = potentialCandidates.map((element) => {\n if (\"img\" === element.nodeName.toLowerCase() && \"picture\" === element.parentElement.nodeName.toLowerCase()) {\n return null;\n }\n let rect;\n if (\"picture\" === element.nodeName.toLowerCase()) {\n const imgElement = element.querySelector(\"img\");\n if (imgElement) {\n rect = imgElement.getBoundingClientRect();\n } else {\n return null;\n }\n } else {\n rect = element.getBoundingClientRect();\n }\n return {\n element,\n rect\n };\n }).filter((item) => item !== null).filter((item) => {\n return item.rect.width > 0 && item.rect.height > 0 && Utils_default.isIntersecting(item.rect);\n }).map((item) => ({\n item,\n area: this._getElementArea(item.rect),\n elementInfo: this._getElementInfo(item.element)\n })).sort((a, b) => b.area - a.area).slice(0, count);\n return topCandidates.map((candidate) => ({\n element: candidate.item.element,\n elementInfo: candidate.elementInfo\n }));\n }\n _getElementArea(rect) {\n const visibleWidth = Math.min(rect.width, (window.innerWidth || document.documentElement.clientWidth) - rect.left);\n const visibleHeight = Math.min(rect.height, (window.innerHeight || document.documentElement.clientHeight) - rect.top);\n return visibleWidth * visibleHeight;\n }\n _getElementInfo(element) {\n const nodeName = element.nodeName.toLowerCase();\n const element_info = {\n type: \"\",\n src: \"\",\n srcset: \"\",\n sizes: \"\",\n sources: [],\n bg_set: [],\n current_src: \"\"\n };\n const css_bg_url_rgx = /url\\(\\s*?['\"]?\\s*?(.+?)\\s*?[\"']?\\s*?\\)/ig;\n if (nodeName === \"img\" && element.srcset) {\n element_info.type = \"img-srcset\";\n element_info.src = element.src;\n element_info.srcset = element.srcset;\n element_info.sizes = element.sizes;\n element_info.current_src = element.currentSrc;\n } else if (nodeName === \"img\") {\n element_info.type = \"img\";\n element_info.src = element.src;\n element_info.current_src = element.currentSrc;\n } else if (nodeName === \"video\") {\n element_info.type = \"img\";\n const source = element.querySelector(\"source\");\n element_info.src = element.poster || (source ? source.src : \"\");\n element_info.current_src = element_info.src;\n } else if (nodeName === \"svg\") {\n const imageElement = element.querySelector(\"image\");\n if (imageElement) {\n element_info.type = \"img\";\n element_info.src = imageElement.getAttribute(\"href\") || \"\";\n element_info.current_src = element_info.src;\n }\n } else if (nodeName === \"picture\") {\n element_info.type = \"picture\";\n const img = element.querySelector(\"img\");\n element_info.src = img ? img.src : \"\";\n element_info.sources = Array.from(element.querySelectorAll(\"source\")).map((source) => ({\n srcset: source.srcset || \"\",\n media: source.media || \"\",\n type: source.type || \"\",\n sizes: source.sizes || \"\"\n }));\n } else {\n const computed_style = window.getComputedStyle(element, null);\n const bg_props = [\n computed_style.getPropertyValue(\"background-image\"),\n getComputedStyle(element, \":after\").getPropertyValue(\"background-image\"),\n getComputedStyle(element, \":before\").getPropertyValue(\"background-image\")\n ].filter((prop) => prop !== \"none\");\n if (bg_props.length === 0) {\n return null;\n }\n const full_bg_prop = bg_props[0];\n element_info.type = \"bg-img\";\n if (full_bg_prop.includes(\"image-set(\")) {\n element_info.type = \"bg-img-set\";\n }\n if (!full_bg_prop || full_bg_prop === \"\" || full_bg_prop.includes(\"data:image\")) {\n return null;\n }\n const matches = [...full_bg_prop.matchAll(css_bg_url_rgx)];\n element_info.bg_set = matches.map((m) => m[1] ? { src: m[1].trim() + (m[2] ? \" \" + m[2].trim() : \"\") } : {});\n if (element_info.bg_set.every((item) => item.src === \"\")) {\n element_info.bg_set = matches.map((m) => m[1] ? { src: m[1].trim() } : {});\n }\n if (element_info.bg_set.length > 0) {\n element_info.src = element_info.bg_set[0].src;\n if (element_info.type === \"bg-img-set\") {\n element_info.src = element_info.bg_set;\n }\n }\n }\n return element_info;\n }\n _initWithFirstElementWithInfo(elements) {\n const firstElementWithInfo = elements.find((item) => item.elementInfo !== null);\n if (!firstElementWithInfo) {\n this.logger.logMessage(\"No LCP candidate found.\");\n this.performanceImages = [];\n return;\n }\n this.performanceImages = [{\n ...firstElementWithInfo.elementInfo,\n label: \"lcp\"\n }];\n }\n _fillATFWithoutDuplications(elements) {\n elements.forEach(({ element, elementInfo }) => {\n if (this._isDuplicateImage(element) || !elementInfo) {\n return;\n }\n this.performanceImages.push({ ...elementInfo, label: \"above-the-fold\" });\n });\n }\n _isDuplicateImage(image) {\n const elementInfo = this._getElementInfo(image);\n if (elementInfo === null) {\n return false;\n }\n const isImageOrVideo = elementInfo.type === \"img\" || elementInfo.type === \"img-srcset\" || elementInfo.type === \"video\";\n const isBgImageOrPicture = elementInfo.type === \"bg-img\" || elementInfo.type === \"bg-img-set\" || elementInfo.type === \"picture\";\n return (isImageOrVideo || isBgImageOrPicture) && this.performanceImages.some((item) => item.src === elementInfo.src);\n }\n getResults() {\n return this.performanceImages;\n }\n };\n var BeaconLcp_default = BeaconLcp;\n\n // src/BeaconLrc.js\n var BeaconLrc = class {\n constructor(config, logger) {\n this.config = config;\n this.logger = logger;\n this.lazyRenderElements = [];\n }\n async run() {\n try {\n const elementsInView = this._getLazyRenderElements();\n if (elementsInView) {\n this._processElements(elementsInView);\n }\n } catch (err) {\n this.errorCode = \"script_error\";\n this.logger.logMessage(\"Script Error: \" + err);\n }\n }\n _getLazyRenderElements() {\n const elements = document.querySelectorAll(this.config.lrc_elements);\n if (elements.length <= 0) {\n return [];\n }\n const validElements = Array.from(elements).filter((element) => !this._skipElement(element));\n return validElements.map((element) => ({\n element,\n depth: this._getElementDepth(element),\n distance: this._getElementDistance(element),\n hash: this._getLocationHash(element)\n }));\n }\n _getElementDepth(element) {\n let depth = 0;\n let parent = element.parentElement;\n while (parent) {\n depth++;\n parent = parent.parentElement;\n }\n return depth;\n }\n _getElementDistance(element) {\n const rect = element.getBoundingClientRect();\n const scrollTop = window.pageYOffset || document.documentElement.scrollTop;\n return Math.max(0, rect.top + scrollTop - (window.innerHeight || document.documentElement.clientHeight));\n }\n _skipElement(element) {\n const skipStrings = this.config.skipStrings || [\"memex\"];\n if (!element || !element.id) return false;\n return skipStrings.some((str) => element.id.toLowerCase().includes(str));\n }\n _shouldSkipElement(element, exclusions) {\n if (!element) return false;\n for (let i = 0; i < exclusions.length; i++) {\n const [attribute, pattern] = exclusions[i];\n const attributeValue = element.getAttribute(attribute);\n if (attributeValue && new RegExp(pattern, \"i\").test(attributeValue)) {\n return true;\n }\n }\n return false;\n }\n _processElements(elements) {\n elements.forEach(({ element, depth, distance, hash }) => {\n if (this._shouldSkipElement(element, this.config.exclusions || [])) {\n return;\n }\n if (\"No hash detected\" === hash) {\n return;\n }\n const color = depth === 2 && distance >= this.config.lrc_threshold || element.parentElement && this._getElementDistance(element.parentElement) === 0 && distance >= this.config.lrc_threshold ? \"green\" : distance === 0 ? \"red\" : \"\";\n this.logger.logColoredMessage(`${\"\t\".repeat(depth)}${element.tagName} (Depth: ${depth}, Distance from viewport top: ${distance}px)`, color);\n this.logger.logColoredMessage(`${\"\t\".repeat(depth)}Location hash: ${hash}`, color);\n this.logger.logColoredMessage(`${\"\t\".repeat(depth)}Dimensions Client Height: ${element.clientHeight}`, color);\n if (depth === 2 && distance >= this.config.lrc_threshold) {\n this.lazyRenderElements.push(hash);\n this.logger.logMessage(`Parent element at depth 2 with distance >= this.config.lrc_threshold pushed with hash: ${hash}`);\n return;\n }\n if (element.parentElement && this._getElementDistance(element.parentElement) === 0 && distance >= this.config.lrc_threshold) {\n this.lazyRenderElements.push(hash);\n this.logger.logMessage(`Child element pushed with hash: ${hash}`);\n }\n });\n }\n _getXPath(element) {\n if (element.id !== \"\") {\n return `//*[@id=\"${element.id}\"]`;\n }\n return this._getElementXPath(element);\n }\n _getElementXPath(element) {\n if (element === document.body) {\n return \"/html/body\";\n }\n const position = this._getElementPosition(element);\n return `${this._getElementXPath(element.parentNode)}/${element.nodeName.toLowerCase()}[${position}]`;\n }\n _getElementPosition(element) {\n let pos = 1;\n let sibling = element.previousElementSibling;\n while (sibling) {\n if (sibling.nodeName === element.nodeName) {\n pos++;\n }\n sibling = sibling.previousElementSibling;\n }\n return pos;\n }\n _getLocationHash(element) {\n return element.hasAttribute(\"data-rocket-location-hash\") ? element.getAttribute(\"data-rocket-location-hash\") : \"No hash detected\";\n }\n getResults() {\n return this.lazyRenderElements;\n }\n };\n var BeaconLrc_default = BeaconLrc;\n\n // src/Logger.js\n var Logger = class {\n constructor(enabled) {\n this.enabled = enabled;\n }\n logMessage(msg) {\n if (!this.enabled) {\n return;\n }\n console.log(msg);\n }\n logColoredMessage(msg, color = \"green\") {\n if (!this.enabled) {\n return;\n }\n console.log(`%c${msg}`, `color: ${color};`);\n }\n };\n var Logger_default = Logger;\n\n // src/BeaconManager.js\n var BeaconManager = class {\n constructor(config) {\n this.config = config;\n this.lcpBeacon = null;\n this.lrcBeacon = null;\n this.infiniteLoopId = null;\n this.errorCode = \"\";\n this.logger = new Logger_default(this.config.debug);\n }\n async init() {\n this.scriptTimer = /* @__PURE__ */ new Date();\n if (!await this._isValidPreconditions()) {\n this._finalize();\n return;\n }\n this.infiniteLoopId = setTimeout(() => {\n this._handleInfiniteLoop();\n }, 1e4);\n const isGeneratedBefore = await this._getGeneratedBefore();\n const shouldGenerateLcp = this.config.status.atf && (isGeneratedBefore === false || isGeneratedBefore.lcp === false);\n const shouldGeneratelrc = this.config.status.lrc && (isGeneratedBefore === false || isGeneratedBefore.lrc === false);\n if (shouldGenerateLcp) {\n this.lcpBeacon = new BeaconLcp_default(this.config, this.logger);\n await this.lcpBeacon.run();\n } else {\n this.logger.logMessage(\"Not running BeaconLcp because data is already available or feature is disabled\");\n }\n if (shouldGeneratelrc) {\n this.lrcBeacon = new BeaconLrc_default(this.config, this.logger);\n await this.lrcBeacon.run();\n } else {\n this.logger.logMessage(\"Not running BeaconLrc because data is already available or feature is disabled\");\n }\n if (shouldGenerateLcp || shouldGeneratelrc) {\n this._saveFinalResultIntoDB();\n } else {\n this.logger.logMessage(\"Not saving results into DB as no beacon features ran.\");\n this._finalize();\n }\n }\n async _isValidPreconditions() {\n const threshold = {\n width: this.config.width_threshold,\n height: this.config.height_threshold\n };\n if (Utils_default.isNotValidScreensize(this.config.is_mobile, threshold)) {\n this.logger.logMessage(\"Bailing out because screen size is not acceptable\");\n return false;\n }\n return true;\n }\n async _getGeneratedBefore() {\n if (!Utils_default.isPageCached()) {\n return false;\n }\n let data_check = new FormData();\n data_check.append(\"action\", \"rocket_check_beacon\");\n data_check.append(\"rocket_beacon_nonce\", this.config.nonce);\n data_check.append(\"url\", this.config.url);\n data_check.append(\"is_mobile\", this.config.is_mobile);\n const beacon_data_response = await fetch(this.config.ajax_url, {\n method: \"POST\",\n credentials: \"same-origin\",\n body: data_check\n }).then((data) => data.json());\n return beacon_data_response.data;\n }\n _saveFinalResultIntoDB() {\n const results = {\n lcp: this.lcpBeacon ? this.lcpBeacon.getResults() : null,\n lrc: this.lrcBeacon ? this.lrcBeacon.getResults() : null\n };\n const data = new FormData();\n data.append(\"action\", \"rocket_beacon\");\n data.append(\"rocket_beacon_nonce\", this.config.nonce);\n data.append(\"url\", this.config.url);\n data.append(\"is_mobile\", this.config.is_mobile);\n data.append(\"status\", this._getFinalStatus());\n data.append(\"results\", JSON.stringify(results));\n fetch(this.config.ajax_url, {\n method: \"POST\",\n credentials: \"same-origin\",\n body: data,\n headers: {\n \"wpr-saas-no-intercept\": true\n }\n }).then((response) => response.json()).then((data2) => {\n this.logger.logMessage(data2.data.lcp);\n }).catch((error) => {\n this.logger.logMessage(error);\n }).finally(() => {\n this._finalize();\n });\n }\n _getFinalStatus() {\n if (\"\" !== this.errorCode) {\n return this.errorCode;\n }\n const scriptTime = (/* @__PURE__ */ new Date() - this.scriptTimer) / 1e3;\n if (10 <= scriptTime) {\n return \"timeout\";\n }\n return \"success\";\n }\n _handleInfiniteLoop() {\n this._saveFinalResultIntoDB();\n }\n _finalize() {\n const beaconscript = document.querySelector('[data-name=\"wpr-wpr-beacon\"]');\n beaconscript.setAttribute(\"beacon-completed\", \"true\");\n clearTimeout(this.infiniteLoopId);\n }\n };\n var BeaconManager_default = BeaconManager;\n\n // src/BeaconEntryPoint.js\n ((rocket_beacon_data) => {\n if (!rocket_beacon_data) {\n return;\n }\n const instance = new BeaconManager_default(rocket_beacon_data);\n if (document.readyState !== \"loading\") {\n setTimeout(() => {\n instance.init();\n }, rocket_beacon_data.delay);\n return;\n }\n document.addEventListener(\"DOMContentLoaded\", () => {\n setTimeout(() => {\n instance.init();\n }, rocket_beacon_data.delay);\n });\n })(window.rocket_beacon_data);\n var BeaconEntryPoint_default = BeaconManager_default;\n})();\n"], - "mappings": "CAAC,IAAM,CAEL,IAAIA,EAAc,KAAM,CACtB,OAAO,qBAAqBC,EAAWC,EAAW,CAChD,MAAMC,EAAc,OAAO,YAAc,SAAS,gBAAgB,YAC5DC,EAAe,OAAO,aAAe,SAAS,gBAAgB,aAC9DC,EAAsBJ,IAAcE,EAAcD,EAAU,OAASE,EAAeF,EAAU,QAC9FI,EAAuB,CAACL,IAAcE,EAAcD,EAAU,OAASE,EAAeF,EAAU,QACtG,OAAOG,GAAuBC,CAChC,CACA,OAAO,cAAe,CACpB,MAAMC,EAAY,SAAS,gBAAgB,aAAe,SAAS,gBAAgB,YAAY,KAAO,SAAS,gBAAgB,YAAY,KAAO,GAClJ,OAAOA,GAAaA,EAAU,SAAS,eAAe,CACxD,CACA,OAAO,eAAeC,EAAM,CAC1B,OAAOA,EAAK,QAAU,GAAKA,EAAK,OAAS,GAAKA,EAAK,MAAQ,OAAO,aAAe,SAAS,gBAAgB,eAAiBA,EAAK,OAAS,OAAO,YAAc,SAAS,gBAAgB,YACzL,CACF,EACIC,EAAgBT,EAGhBU,EAAY,KAAM,CACpB,YAAYC,EAAQC,EAAQ,CAC1B,KAAK,OAASD,EACd,KAAK,kBAAoB,CAAC,EAC1B,KAAK,OAASC,CAChB,CACA,MAAM,KAAM,CACV,GAAI,CACF,MAAMC,EAAwB,KAAK,uBAAuB,GAAQ,EAC9DA,IACF,KAAK,8BAA8BA,CAAqB,EACxD,KAAK,4BAA4BA,CAAqB,EAE1D,OAASC,EAAK,CACZ,KAAK,UAAY,eACjB,KAAK,OAAO,WAAW,iBAAmBA,CAAG,CAC/C,CACF,CACA,uBAAuBC,EAAO,CAC5B,MAAMC,EAAc,S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AClC,CACF,EACIC,EAAwBV,GAG1BW,GAAuB,CACvB,GAAI,CAACA,EACH,OAEF,MAAMC,EAAW,IAAIF,EAAsBC,CAAkB,EAC7D,GAAI,SAAS,aAAe,UAAW,CACrC,WAAW,IAAM,CACfC,EAAS,KAAK,CAChB,EAAGD,EAAmB,KAAK,EAC3B,MACF,CACA,SAAS,iBAAiB,mBAAoB,IAAM,CAClD,WAAW,IAAM,CACfC,EAAS,KAAK,CAChB,EAAGD,EAAmB,KAAK,CAC7B,CAAC,CACH,GAAG,OAAO,kBAAkB,EAC5B,IAAIE,EAA2BH,CACjC,GAAG", - "names": ["BeaconUtils", "is_mobile", "threshold", "screenWidth", "screenHeight", "isNotValidForMobile", "isNotValidForDesktop", "signature", "rect", "Utils_default", "BeaconLcp", "config", "logger", "above_the_fold_images", "err", "count", "lcpElements", "element", "imgElement", "item", "a", "b", "candidate", "visibleWidth", "visibleHeight", "nodeName", "element_info", "css_bg_url_rgx", "source", "imageElement", "img", "bg_props", "prop", "full_bg_prop", "matches", "m", "elements", "firstElementWithInfo", "elementInfo", "image", "isImageOrVideo", "isBgImageOrPicture", "BeaconLcp_default", "BeaconLrc", "elementsInView", "depth", "parent", "scrollTop", "skipStrings", "str", "exclusions", "i", "attribute", "pattern", "attributeValue", "distance", "hash", "color", "position", "pos", "sibling", "BeaconLrc_default", "Logger", "enabled", "msg", "Logger_default", "BeaconManager", "isGeneratedBefore", "shouldGenerateLcp", "shouldGeneratelrc", "data_check", "data", "results", "response", "data2", "error", "BeaconManager_default", "rocket_beacon_data", "instance", "BeaconEntryPoint_default"] + "sourcesContent": ["(() => {\n // src/Utils.js\n var BeaconUtils = class {\n static isNotValidScreensize(is_mobile, threshold) {\n const screenWidth = window.innerWidth || document.documentElement.clientWidth;\n const screenHeight = window.innerHeight || document.documentElement.clientHeight;\n const isNotValidForMobile = is_mobile && (screenWidth > threshold.width || screenHeight > threshold.height);\n const isNotValidForDesktop = !is_mobile && (screenWidth < threshold.width || screenHeight < threshold.height);\n return isNotValidForMobile || isNotValidForDesktop;\n }\n static isPageCached() {\n const signature = document.documentElement.nextSibling && document.documentElement.nextSibling.data ? document.documentElement.nextSibling.data : \"\";\n return signature && signature.includes(\"Debug: cached\");\n }\n static isIntersecting(rect) {\n return rect.bottom >= 0 && rect.right >= 0 && rect.top <= (window.innerHeight || document.documentElement.clientHeight) && rect.left <= (window.innerWidth || document.documentElement.clientWidth);\n }\n };\n var Utils_default = BeaconUtils;\n\n // src/BeaconLcp.js\n var BeaconLcp = class {\n constructor(config, logger) {\n this.config = config;\n this.performanceImages = [];\n this.logger = logger;\n }\n async run() {\n try {\n const above_the_fold_images = this._generateLcpCandidates(Infinity);\n if (above_the_fold_images) {\n this._initWithFirstElementWithInfo(above_the_fold_images);\n this._fillATFWithoutDuplications(above_the_fold_images);\n }\n } catch (err) {\n this.errorCode = \"script_error\";\n this.logger.logMessage(\"Script Error: \" + err);\n }\n }\n _generateLcpCandidates(count) {\n const lcpElements = document.querySelectorAll(this.config.elements);\n if (lcpElements.length <= 0) {\n return [];\n }\n const potentialCandidates = Array.from(lcpElements);\n const topCandidates = potentialCandidates.map((element) => {\n if (\"img\" === element.nodeName.toLowerCase() && \"picture\" === element.parentElement.nodeName.toLowerCase()) {\n return null;\n }\n let rect;\n if (\"picture\" === element.nodeName.toLowerCase()) {\n const imgElement = element.querySelector(\"img\");\n if (imgElement) {\n rect = imgElement.getBoundingClientRect();\n } else {\n return null;\n }\n } else {\n rect = element.getBoundingClientRect();\n }\n return {\n element,\n rect\n };\n }).filter((item) => item !== null).filter((item) => {\n return item.rect.width > 0 && item.rect.height > 0 && Utils_default.isIntersecting(item.rect);\n }).map((item) => ({\n item,\n area: this._getElementArea(item.rect),\n elementInfo: this._getElementInfo(item.element)\n })).sort((a, b) => b.area - a.area).slice(0, count);\n return topCandidates.map((candidate) => ({\n element: candidate.item.element,\n elementInfo: candidate.elementInfo\n }));\n }\n _getElementArea(rect) {\n const visibleWidth = Math.min(rect.width, (window.innerWidth || document.documentElement.clientWidth) - rect.left);\n const visibleHeight = Math.min(rect.height, (window.innerHeight || document.documentElement.clientHeight) - rect.top);\n return visibleWidth * visibleHeight;\n }\n _getElementInfo(element) {\n const nodeName = element.nodeName.toLowerCase();\n const element_info = {\n type: \"\",\n src: \"\",\n srcset: \"\",\n sizes: \"\",\n sources: [],\n bg_set: [],\n current_src: \"\"\n };\n const css_bg_url_rgx = /url\\(\\s*?['\"]?\\s*?(.+?)\\s*?[\"']?\\s*?\\)/ig;\n if (nodeName === \"img\" && element.srcset) {\n element_info.type = \"img-srcset\";\n element_info.src = element.src;\n element_info.srcset = element.srcset;\n element_info.sizes = element.sizes;\n element_info.current_src = element.currentSrc;\n } else if (nodeName === \"img\") {\n element_info.type = \"img\";\n element_info.src = element.src;\n element_info.current_src = element.currentSrc;\n } else if (nodeName === \"video\") {\n element_info.type = \"img\";\n const source = element.querySelector(\"source\");\n element_info.src = element.poster || (source ? source.src : \"\");\n element_info.current_src = element_info.src;\n } else if (nodeName === \"svg\") {\n const imageElement = element.querySelector(\"image\");\n if (imageElement) {\n element_info.type = \"img\";\n element_info.src = imageElement.getAttribute(\"href\") || \"\";\n element_info.current_src = element_info.src;\n }\n } else if (nodeName === \"picture\") {\n element_info.type = \"picture\";\n const img = element.querySelector(\"img\");\n element_info.src = img ? img.src : \"\";\n element_info.sources = Array.from(element.querySelectorAll(\"source\")).map((source) => ({\n srcset: source.srcset || \"\",\n media: source.media || \"\",\n type: source.type || \"\",\n sizes: source.sizes || \"\"\n }));\n } else {\n const computed_style = window.getComputedStyle(element, null);\n const bg_props = [\n computed_style.getPropertyValue(\"background-image\"),\n getComputedStyle(element, \":after\").getPropertyValue(\"background-image\"),\n getComputedStyle(element, \":before\").getPropertyValue(\"background-image\")\n ].filter((prop) => prop !== \"none\");\n if (bg_props.length === 0) {\n return null;\n }\n const full_bg_prop = bg_props[0];\n element_info.type = \"bg-img\";\n if (full_bg_prop.includes(\"image-set(\")) {\n element_info.type = \"bg-img-set\";\n }\n if (!full_bg_prop || full_bg_prop === \"\" || full_bg_prop.includes(\"data:image\")) {\n return null;\n }\n const matches = [...full_bg_prop.matchAll(css_bg_url_rgx)];\n element_info.bg_set = matches.map((m) => m[1] ? { src: m[1].trim() + (m[2] ? \" \" + m[2].trim() : \"\") } : {});\n if (element_info.bg_set.every((item) => item.src === \"\")) {\n element_info.bg_set = matches.map((m) => m[1] ? { src: m[1].trim() } : {});\n }\n if (element_info.bg_set.length > 0) {\n element_info.src = element_info.bg_set[0].src;\n if (element_info.type === \"bg-img-set\") {\n element_info.src = element_info.bg_set;\n }\n }\n }\n return element_info;\n }\n _initWithFirstElementWithInfo(elements) {\n const firstElementWithInfo = elements.find((item) => item.elementInfo !== null);\n if (!firstElementWithInfo) {\n this.logger.logMessage(\"No LCP candidate found.\");\n this.performanceImages = [];\n return;\n }\n this.performanceImages = [{\n ...firstElementWithInfo.elementInfo,\n label: \"lcp\"\n }];\n }\n _fillATFWithoutDuplications(elements) {\n elements.forEach(({ element, elementInfo }) => {\n if (this._isDuplicateImage(element) || !elementInfo) {\n return;\n }\n this.performanceImages.push({ ...elementInfo, label: \"above-the-fold\" });\n });\n }\n _isDuplicateImage(image) {\n const elementInfo = this._getElementInfo(image);\n if (elementInfo === null) {\n return false;\n }\n const isImageOrVideo = elementInfo.type === \"img\" || elementInfo.type === \"img-srcset\" || elementInfo.type === \"video\";\n const isBgImageOrPicture = elementInfo.type === \"bg-img\" || elementInfo.type === \"bg-img-set\" || elementInfo.type === \"picture\";\n return (isImageOrVideo || isBgImageOrPicture) && this.performanceImages.some((item) => item.src === elementInfo.src);\n }\n getResults() {\n return this.performanceImages;\n }\n };\n var BeaconLcp_default = BeaconLcp;\n\n // src/BeaconLrc.js\n var BeaconLrc = class {\n constructor(config, logger) {\n this.config = config;\n this.logger = logger;\n this.lazyRenderElements = [];\n }\n async run() {\n try {\n const elementsInView = this._getLazyRenderElements();\n if (elementsInView) {\n this._processElements(elementsInView);\n }\n } catch (err) {\n this.errorCode = \"script_error\";\n this.logger.logMessage(\"Script Error: \" + err);\n }\n }\n _getLazyRenderElements() {\n const elements = document.querySelectorAll(\"[data-rocket-location-hash]\");\n if (elements.length <= 0) {\n return [];\n }\n const validElements = Array.from(elements).filter((element) => !this._skipElement(element));\n return validElements.map((element) => ({\n element,\n depth: this._getElementDepth(element),\n distance: this._getElementDistance(element),\n hash: this._getLocationHash(element)\n }));\n }\n _getElementDepth(element) {\n let depth = 0;\n let parent = element.parentElement;\n while (parent) {\n depth++;\n parent = parent.parentElement;\n }\n return depth;\n }\n _getElementDistance(element) {\n const rect = element.getBoundingClientRect();\n const scrollTop = window.pageYOffset || document.documentElement.scrollTop;\n return Math.max(0, rect.top + scrollTop);\n }\n _skipElement(element) {\n const skipStrings = this.config.skipStrings || [\"memex\"];\n if (!element || !element.id) return false;\n return skipStrings.some((str) => element.id.toLowerCase().includes(str));\n }\n _shouldSkipElement(element, exclusions) {\n if (!element) return false;\n for (let i = 0; i < exclusions.length; i++) {\n const [attribute, pattern] = exclusions[i];\n const attributeValue = element.getAttribute(attribute);\n if (attributeValue && new RegExp(pattern, \"i\").test(attributeValue)) {\n return true;\n }\n }\n return false;\n }\n _processElements(elements) {\n elements.forEach(({ element, depth, distance, hash }) => {\n if (this._shouldSkipElement(element, this.config.exclusions || [])) {\n return;\n }\n if (\"No hash detected\" === hash) {\n return;\n }\n const can_push_hash = element.parentElement && this._getElementDistance(element.parentElement) < this.config.lrc_threshold && distance > this.config.lrc_threshold;\n const color = can_push_hash ? \"green\" : distance === 0 ? \"red\" : \"\";\n this.logger.logColoredMessage(`${\"\t\".repeat(depth)}${element.tagName} (Depth: ${depth}, Distance from viewport top: ${distance}px)`, color);\n this.logger.logColoredMessage(`${\"\t\".repeat(depth)}Location hash: ${hash}`, color);\n this.logger.logColoredMessage(`${\"\t\".repeat(depth)}Dimensions Client Height: ${element.clientHeight}`, color);\n if (can_push_hash) {\n this.lazyRenderElements.push(hash);\n this.logger.logMessage(`Element pushed with hash: ${hash}`);\n }\n });\n }\n _getXPath(element) {\n if (element.id !== \"\") {\n return `//*[@id=\"${element.id}\"]`;\n }\n return this._getElementXPath(element);\n }\n _getElementXPath(element) {\n if (element === document.body) {\n return \"/html/body\";\n }\n const position = this._getElementPosition(element);\n return `${this._getElementXPath(element.parentNode)}/${element.nodeName.toLowerCase()}[${position}]`;\n }\n _getElementPosition(element) {\n let pos = 1;\n let sibling = element.previousElementSibling;\n while (sibling) {\n if (sibling.nodeName === element.nodeName) {\n pos++;\n }\n sibling = sibling.previousElementSibling;\n }\n return pos;\n }\n _getLocationHash(element) {\n return element.hasAttribute(\"data-rocket-location-hash\") ? element.getAttribute(\"data-rocket-location-hash\") : \"No hash detected\";\n }\n getResults() {\n return this.lazyRenderElements;\n }\n };\n var BeaconLrc_default = BeaconLrc;\n\n // src/Logger.js\n var Logger = class {\n constructor(enabled) {\n this.enabled = enabled;\n }\n logMessage(msg) {\n if (!this.enabled) {\n return;\n }\n console.log(msg);\n }\n logColoredMessage(msg, color = \"green\") {\n if (!this.enabled) {\n return;\n }\n console.log(`%c${msg}`, `color: ${color};`);\n }\n };\n var Logger_default = Logger;\n\n // src/BeaconManager.js\n var BeaconManager = class {\n constructor(config) {\n this.config = config;\n this.lcpBeacon = null;\n this.lrcBeacon = null;\n this.infiniteLoopId = null;\n this.errorCode = \"\";\n this.logger = new Logger_default(this.config.debug);\n }\n async init() {\n this.scriptTimer = /* @__PURE__ */ new Date();\n if (!await this._isValidPreconditions()) {\n this._finalize();\n return;\n }\n this.infiniteLoopId = setTimeout(() => {\n this._handleInfiniteLoop();\n }, 1e4);\n const isGeneratedBefore = await this._getGeneratedBefore();\n const shouldGenerateLcp = this.config.status.atf && (isGeneratedBefore === false || isGeneratedBefore.lcp === false);\n const shouldGeneratelrc = this.config.status.lrc && (isGeneratedBefore === false || isGeneratedBefore.lrc === false);\n if (shouldGenerateLcp) {\n this.lcpBeacon = new BeaconLcp_default(this.config, this.logger);\n await this.lcpBeacon.run();\n } else {\n this.logger.logMessage(\"Not running BeaconLcp because data is already available or feature is disabled\");\n }\n if (shouldGeneratelrc) {\n this.lrcBeacon = new BeaconLrc_default(this.config, this.logger);\n await this.lrcBeacon.run();\n } else {\n this.logger.logMessage(\"Not running BeaconLrc because data is already available or feature is disabled\");\n }\n if (shouldGenerateLcp || shouldGeneratelrc) {\n this._saveFinalResultIntoDB();\n } else {\n this.logger.logMessage(\"Not saving results into DB as no beacon features ran.\");\n this._finalize();\n }\n }\n async _isValidPreconditions() {\n const threshold = {\n width: this.config.width_threshold,\n height: this.config.height_threshold\n };\n if (Utils_default.isNotValidScreensize(this.config.is_mobile, threshold)) {\n this.logger.logMessage(\"Bailing out because screen size is not acceptable\");\n return false;\n }\n return true;\n }\n async _getGeneratedBefore() {\n if (!Utils_default.isPageCached()) {\n return false;\n }\n let data_check = new FormData();\n data_check.append(\"action\", \"rocket_check_beacon\");\n data_check.append(\"rocket_beacon_nonce\", this.config.nonce);\n data_check.append(\"url\", this.config.url);\n data_check.append(\"is_mobile\", this.config.is_mobile);\n const beacon_data_response = await fetch(this.config.ajax_url, {\n method: \"POST\",\n credentials: \"same-origin\",\n body: data_check\n }).then((data) => data.json());\n return beacon_data_response.data;\n }\n _saveFinalResultIntoDB() {\n const results = {\n lcp: this.lcpBeacon ? this.lcpBeacon.getResults() : null,\n lrc: this.lrcBeacon ? this.lrcBeacon.getResults() : null\n };\n const data = new FormData();\n data.append(\"action\", \"rocket_beacon\");\n data.append(\"rocket_beacon_nonce\", this.config.nonce);\n data.append(\"url\", this.config.url);\n data.append(\"is_mobile\", this.config.is_mobile);\n data.append(\"status\", this._getFinalStatus());\n data.append(\"results\", JSON.stringify(results));\n fetch(this.config.ajax_url, {\n method: \"POST\",\n credentials: \"same-origin\",\n body: data,\n headers: {\n \"wpr-saas-no-intercept\": true\n }\n }).then((response) => response.json()).then((data2) => {\n this.logger.logMessage(data2.data.lcp);\n }).catch((error) => {\n this.logger.logMessage(error);\n }).finally(() => {\n this._finalize();\n });\n }\n _getFinalStatus() {\n if (\"\" !== this.errorCode) {\n return this.errorCode;\n }\n const scriptTime = (/* @__PURE__ */ new Date() - this.scriptTimer) / 1e3;\n if (10 <= scriptTime) {\n return \"timeout\";\n }\n return \"success\";\n }\n _handleInfiniteLoop() {\n this._saveFinalResultIntoDB();\n }\n _finalize() {\n const beaconscript = document.querySelector('[data-name=\"wpr-wpr-beacon\"]');\n beaconscript.setAttribute(\"beacon-completed\", \"true\");\n clearTimeout(this.infiniteLoopId);\n }\n };\n var BeaconManager_default = BeaconManager;\n\n // src/BeaconEntryPoint.js\n ((rocket_beacon_data) => {\n if (!rocket_beacon_data) {\n return;\n }\n const instance = new BeaconManager_default(rocket_beacon_data);\n if (document.readyState !== \"loading\") {\n setTimeout(() => {\n instance.init();\n }, rocket_beacon_data.delay);\n return;\n }\n document.addEventListener(\"DOMContentLoaded\", () => {\n setTimeout(() => {\n instance.init();\n }, rocket_beacon_data.delay);\n });\n })(window.rocket_beacon_data);\n var BeaconEntryPoint_default = BeaconManager_default;\n})();\n"], + "mappings": "CAAC,IAAM,CAEL,IAAIA,EAAc,KAAM,CACtB,OAAO,qBAAqBC,EAAWC,EAAW,CAChD,MAAMC,EAAc,OAAO,YAAc,SAAS,gBAAgB,YAC5DC,EAAe,OAAO,aAAe,SAAS,gBAAgB,aAC9DC,EAAsBJ,IAAcE,EAAcD,EAAU,OAASE,EAAeF,EAAU,QAC9FI,EAAuB,CAACL,IAAcE,EAAcD,EAAU,OAASE,EAAeF,EAAU,QACtG,OAAOG,GAAuBC,CAChC,CACA,OAAO,cAAe,CACpB,MAAMC,EAAY,SAAS,gBAAgB,aAAe,SAAS,gBAAgB,YAAY,KAAO,SAAS,gBAAgB,YAAY,KAAO,GAClJ,OAAOA,GAAaA,EAAU,SAAS,eAAe,CACxD,CACA,OAAO,eAAeC,EAAM,CAC1B,OAAOA,EAAK,QAAU,GAAKA,EAAK,OAAS,GAAKA,EAAK,MAAQ,OAAO,aAAe,SAAS,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K,UAGV,KADgC,IAAI,KAAS,KAAK,aAAe,IAE5D,UAEF,SACT,CACA,qBAAsB,CACpB,KAAK,uBAAuB,CAC9B,CACA,WAAY,CACW,SAAS,cAAc,8BAA8B,EAC7D,aAAa,mBAAoB,MAAM,EACpD,aAAa,KAAK,cAAc,CAClC,CACF,EACIC,EAAwBV,GAG1BW,GAAuB,CACvB,GAAI,CAACA,EACH,OAEF,MAAMC,EAAW,IAAIF,EAAsBC,CAAkB,EAC7D,GAAI,SAAS,aAAe,UAAW,CACrC,WAAW,IAAM,CACfC,EAAS,KAAK,CAChB,EAAGD,EAAmB,KAAK,EAC3B,MACF,CACA,SAAS,iBAAiB,mBAAoB,IAAM,CAClD,WAAW,IAAM,CACfC,EAAS,KAAK,CAChB,EAAGD,EAAmB,KAAK,CAC7B,CAAC,CACH,GAAG,OAAO,kBAAkB,EAC5B,IAAIE,EAA2BH,CACjC,GAAG", + "names": ["BeaconUtils", "is_mobile", "threshold", "screenWidth", "screenHeight", "isNotValidForMobile", "isNotValidForDesktop", "signature", "rect", "Utils_default", "BeaconLcp", "config", "logger", "above_the_fold_images", "err", "count", "lcpElements", "element", "imgElement", "item", "a", "b", "candidate", "visibleWidth", "visibleHeight", "nodeName", "element_info", "css_bg_url_rgx", "source", "imageElement", "img", "bg_props", "prop", "full_bg_prop", "matches", "m", "elements", "firstElementWithInfo", "elementInfo", "image", "isImageOrVideo", "isBgImageOrPicture", "BeaconLcp_default", "BeaconLrc", "elementsInView", "depth", "parent", "scrollTop", "skipStrings", "str", "exclusions", "i", "attribute", "pattern", "attributeValue", "distance", "hash", "can_push_hash", "color", "position", "pos", "sibling", "BeaconLrc_default", "Logger", "enabled", "msg", "Logger_default", "BeaconManager", "isGeneratedBefore", "shouldGenerateLcp", "shouldGeneratelrc", "data_check", "data", "results", "response", "data2", "error", "BeaconManager_default", "rocket_beacon_data", "instance", "BeaconEntryPoint_default"] } diff --git a/inc/Engine/Optimization/LazyRenderContent/Frontend/Controller.php b/inc/Engine/Optimization/LazyRenderContent/Frontend/Controller.php index 8308990c49..b1a473646e 100644 --- a/inc/Engine/Optimization/LazyRenderContent/Frontend/Controller.php +++ b/inc/Engine/Optimization/LazyRenderContent/Frontend/Controller.php @@ -138,25 +138,6 @@ public function add_hashes( $html ) { * @return array */ public function add_custom_data( array $data ): array { - $elements = [ - 'div', - 'main', - 'footer', - 'section', - 'article', - 'header', - ]; - - /** - * Filters the array of elements - * - * @since 3.17 - * - * @param array $formats Array of elements - */ - $elements = wpm_apply_filters_typed( 'array', 'rocket_lrc_elements', $elements ); - - $data['lrc_elements'] = implode( ', ', $elements ); $data['status']['lrc'] = $this->context->is_allowed(); /** diff --git a/inc/Engine/Optimization/LazyRenderContent/Frontend/Processor/Dom.php b/inc/Engine/Optimization/LazyRenderContent/Frontend/Processor/Dom.php index 3ee5a3b45f..a96f2388c4 100644 --- a/inc/Engine/Optimization/LazyRenderContent/Frontend/Processor/Dom.php +++ b/inc/Engine/Optimization/LazyRenderContent/Frontend/Processor/Dom.php @@ -7,6 +7,9 @@ use WP_Rocket\Logger\Logger; class Dom implements ProcessorInterface { + + use HelperTrait; + /** * Add hashes to the HTML elements * @@ -41,7 +44,7 @@ public function add_hashes( $html ) { return $html; } - $this->add_hash_to_element( $body, 2 ); + $this->add_hash_to_element( $body, $this->get_depth() ); return $dom->saveHTML(); } @@ -57,14 +60,7 @@ private function add_hash_to_element( $element, $depth ) { return; } - $skip_tags = [ - 'DIV', - 'MAIN', - 'FOOTER', - 'SECTION', - 'ARTICLE', - 'HEADER', - ]; + $processed_tags = $this->get_processed_tags(); static $count = 0; @@ -76,7 +72,7 @@ private function add_hash_to_element( $element, $depth ) { if ( XML_ELEMENT_NODE !== $child->nodeType // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase || - ! in_array( strtoupper( $child->tagName ), $skip_tags, true ) // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase + ! in_array( strtoupper( $child->tagName ), $processed_tags, true ) // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase ) { continue; } diff --git a/inc/Engine/Optimization/LazyRenderContent/Frontend/Processor/HelperTrait.php b/inc/Engine/Optimization/LazyRenderContent/Frontend/Processor/HelperTrait.php new file mode 100644 index 0000000000..8a91d3d97e --- /dev/null +++ b/inc/Engine/Optimization/LazyRenderContent/Frontend/Processor/HelperTrait.php @@ -0,0 +1,47 @@ +<(' . implode( '|', $skip_tags ) . ')[^>]*>)/is', $element, $matches, PREG_SET_ORDER ); + $processed_tags = $this->get_processed_tags(); + + $result = preg_match_all( '/(?><(' . implode( '|', $processed_tags ) . ')[^>]*>)/is', $element, $matches, PREG_SET_ORDER ); if ( ! $result ) { Logger::error( 'No elements found in the HTML content.', [ 'LazyRenderContent' ] ); diff --git a/inc/Engine/Optimization/LazyRenderContent/Frontend/Processor/SimpleHtmlDom.php b/inc/Engine/Optimization/LazyRenderContent/Frontend/Processor/SimpleHtmlDom.php index 3c7f88a2d4..022f0f6ad3 100644 --- a/inc/Engine/Optimization/LazyRenderContent/Frontend/Processor/SimpleHtmlDom.php +++ b/inc/Engine/Optimization/LazyRenderContent/Frontend/Processor/SimpleHtmlDom.php @@ -9,6 +9,9 @@ use WP_Rocket\Logger\Logger; class SimpleHtmlDom implements ProcessorInterface { + + use HelperTrait; + /** * Add hashes to the HTML elements * @@ -27,7 +30,7 @@ public function add_hashes( $html ) { return $html; } - $this->add_hash_to_element( $body, 2 ); + $this->add_hash_to_element( $body, $this->get_depth() ); return $dom->save(); } @@ -43,19 +46,12 @@ private function add_hash_to_element( $element, $depth ) { return; } - $skip_tags = [ - 'DIV', - 'MAIN', - 'FOOTER', - 'SECTION', - 'ARTICLE', - 'HEADER', - ]; + $processed_tags = $this->get_processed_tags(); static $count = 0; foreach ( $element->childNodes() as $child ) { - if ( ! in_array( strtoupper( $child->getTag() ), $skip_tags, true ) ) { + if ( ! in_array( strtoupper( $child->getTag() ), $processed_tags, true ) ) { continue; } diff --git a/package.json b/package.json index de1c9e83d3..018b79d688 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ "watchify": "^4.0.0", "webpack": "^5.76.0", "webpack-cli": "^4.9.1", - "wp-rocket-scripts": "^1.0.4", + "wp-rocket-scripts": "github:wp-media/rocket-scripts#enhancement/depend-on-php", "yargs": "^17.3.0" } } diff --git a/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/output_w_beacon.html b/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/output_w_beacon.html index 1fc89a476a..a4fe6228a8 100644 --- a/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/output_w_beacon.html +++ b/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/output_w_beacon.html @@ -3,5 +3,5 @@ Test - + diff --git a/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/output_with_beacon_and_atf_opt.html b/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/output_with_beacon_and_atf_opt.html index 7d77c7ec39..8e8bf4b6da 100644 --- a/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/output_with_beacon_and_atf_opt.html +++ b/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/output_with_beacon_and_atf_opt.html @@ -4,5 +4,5 @@ Sample alt - + diff --git a/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/output_with_beacon_and_only_lrc_opt.html b/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/output_with_beacon_and_only_lrc_opt.html index f391208329..7016432590 100644 --- a/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/output_with_beacon_and_only_lrc_opt.html +++ b/tests/Fixtures/inc/Engine/Common/PerformanceHints/Frontend/Subscriber/HTML/output_with_beacon_and_only_lrc_opt.html @@ -8,5 +8,5 @@
- + diff --git a/tests/Fixtures/inc/Engine/Optimization/LazyRenderContent/Frontend/Controller/addCustomData.php b/tests/Fixtures/inc/Engine/Optimization/LazyRenderContent/Frontend/Controller/addCustomData.php index 2af6415657..82d36afecb 100644 --- a/tests/Fixtures/inc/Engine/Optimization/LazyRenderContent/Frontend/Controller/addCustomData.php +++ b/tests/Fixtures/inc/Engine/Optimization/LazyRenderContent/Frontend/Controller/addCustomData.php @@ -7,7 +7,6 @@ ], 'data' => [], 'expected' => [ - 'lrc_elements' => 'div, main, footer, section, article, header', 'status' => [ 'lrc' => true, ], @@ -20,7 +19,6 @@ ], 'data' => [], 'expected' => [ - 'lrc_elements' => 'div, main, footer, section, article, header', 'status' => [ 'lrc' => false, ],