wp-media / wp-rocket

Performance optimization plugin for WordPress
https://wp-rocket.me
GNU General Public License v2.0
687 stars 215 forks source link

Filter to exclude elements from LCP #6757

Open DahmaniAdame opened 2 months ago

DahmaniAdame commented 2 months ago

Before submitting an issue please check that you’ve completed the following steps:

Describe the bug In some edge cases, discovered LCP will be inaccurate and getting the proper element will require extensive logic and comparison, or will just not be possible.

We need a filter to help exclude LCP element depending on their selector or image path fragment.

The following worked on a website with the issue:

Replacing:

const firstElementWithInfo = elements.find(item => item.elementInfo !== null);

Under _initWithFirstElementWithInfo(elements) { ... } with:

const selectorsToExclude = ['.selector'];
const imagesToExclude = ['frament/path/to/image.jpg'];

const firstElementWithInfo = elements.find(item => 
  item.elementInfo !== null && 
  !selectorsToExclude.some(selector => item.element.matches(selector)) &&
  !imagesToExclude.some(image => 
    (item.elementInfo.src && item.elementInfo.src.includes(image)) || 
    (item.elementInfo.srcset && item.elementInfo.srcset.includes(image))
  )
);

To Reproduce For testing, you can simulate it using:

https://woodmart.xtemos.com/blog/category/wooden-accessories/?opt=blog_default

By adding the following style to simulate the issue:

.main-page-wrapper {
    background-image: url(https://images.pexels.com/photos/214574/pexels-photo-214574.jpeg?auto=compress&cs=tinysrgb&w=50&dpr=1);
    background-repeat: no-repeat;
}

and test excluding either:

const selectorsToExclude = ['.main-page-wrapper'];
const imagesToExclude = ['214574/pexels-photo-214574.jpeg'];

Expected behavior Customers, support, product (for known layouts), should be able to exclude inaccurate LCP element when needed.

Screenshots N/A

Additional context Slack discussion - https://wp-media.slack.com/archives/C08N8J6VC/p1719941962200769?thread_ts=1719857870.817579&cid=C08N8J6VC

Acceptance Criteria (for WP Media team use only) Clear instructions for developers, to be added before the grooming

alfonso100 commented 2 months ago

I applied the suggested code on the customer website, and it succeed in skipping the matching element frament/path/to/image.jpg