diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.yml index b9c9ba8b9..38d030fb8 100755 --- a/.github/workflows/test-e2e.yml +++ b/.github/workflows/test-e2e.yml @@ -12,7 +12,7 @@ concurrency: jobs: e2e: if: ( github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name ) && ( github.actor != 'dependabot[bot]' ) - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 - name: Setup Node diff --git a/assets/js/modules/__tests__/background.test.js b/assets/js/modules/__tests__/background.test.js index 9f10247d0..5b8549ed8 100644 --- a/assets/js/modules/__tests__/background.test.js +++ b/assets/js/modules/__tests__/background.test.js @@ -33,6 +33,7 @@ describe('optmlBackground', () => { mockObserver = { observe: jest.fn(), + unobserve: jest.fn(), disconnect: jest.fn() }; @@ -44,6 +45,44 @@ describe('optmlBackground', () => { }); describe('setupBackgroundImageObservation', () => { + test('issue 1216: keeps watching pending elements after the first one is lazyloaded', () => { + let classCallback; + const classObserverInstance = { observe: jest.fn(), disconnect: jest.fn() }; + global.MutationObserver = jest.fn((callback) => { + classCallback = callback; + return classObserverInstance; + }); + document.body.innerHTML = '
'; + const [first, second] = document.querySelectorAll('div'); + optmlDomUtils.getUniqueSelector.mockReturnValue('div.bg'); + optmlDomUtils.hasBackgroundImage.mockReturnValue(true); + + optmlBackground.setupBackgroundImageObservation([first, second], '.bg', new Map(), mockObserver); + + first.classList.add('optml-bg-lazyloaded'); + classCallback([{ target: first }]); + expect(classObserverInstance.disconnect).not.toHaveBeenCalled(); + + second.classList.add('optml-bg-lazyloaded'); + classCallback([{ target: second }]); + expect(mockObserver.observe).toHaveBeenCalledWith(first); + expect(mockObserver.observe).toHaveBeenCalledWith(second); + expect(classObserverInstance.disconnect).toHaveBeenCalledTimes(1); + }); + + test('issue 1216: re-observes a lazyloaded element so an already observed img gets a fresh callback', () => { + document.body.innerHTML = ''; + const img = document.querySelector('img'); + optmlDomUtils.getUniqueSelector.mockReturnValue('img.bg'); + optmlDomUtils.hasBackgroundImage.mockReturnValue(true); + + optmlBackground.setupBackgroundImageObservation([img], '.bg', new Map(), mockObserver); + + expect(mockObserver.unobserve).toHaveBeenCalledWith(img); + expect(mockObserver.observe).toHaveBeenCalledWith(img); + expect(mockObserver.unobserve.mock.invocationCallOrder[0]).toBeLessThan(mockObserver.observe.mock.invocationCallOrder[0]); + }); + test('should setup observation for elements', () => { document.body.innerHTML = `
@@ -294,6 +333,17 @@ describe('optmlBackground', () => { expect(result.selectorMap.get('.bg-element')).toEqual([]); }); + test('issue 1216: populates the provided selector map shared with the observer', () => { + document.body.innerHTML = '
'; + optmlDomUtils.getUniqueSelector.mockReturnValue('div.bg-element'); + const observerSelectorMap = new Map(); + + const result = optmlBackground.processBackgroundSelectors(['.bg-element'], mockObserver, observerSelectorMap); + + expect(result.selectorMap).toBe(observerSelectorMap); + expect(observerSelectorMap.get('.bg-element')).toEqual([]); + }); + test('should log warning for selectors with no elements', () => { const result = optmlBackground.processBackgroundSelectors(['.non-existent'], mockObserver); diff --git a/assets/js/modules/__tests__/dom-utils.test.js b/assets/js/modules/__tests__/dom-utils.test.js index 3a7031f74..1bb36abed 100644 --- a/assets/js/modules/__tests__/dom-utils.test.js +++ b/assets/js/modules/__tests__/dom-utils.test.js @@ -101,6 +101,20 @@ describe('optmlDomUtils', () => { expect(selector).toContain('another-class'); }); + test.each([ + ['only the lazyload class', 'optml-bg-lazyloaded'], + ['a whitespace-only class attribute', ' '], + ])('should return a valid selector for an element with %s', (_label, classAttribute) => { + document.body.innerHTML = '
'; + const element = document.querySelectorAll('#c > div')[1]; + element.setAttribute('class', classAttribute); + + const selector = optmlDomUtils.getUniqueSelector(element); + + expect(selector).toBe('#c > div:nth-of-type(2)'); + expect(document.querySelector(selector)).toBe(element); + }); + test('should handle element without classes', () => { document.body.innerHTML = '
'; const element = document.querySelector('div'); @@ -293,12 +307,15 @@ describe('optmlDomUtils', () => { describe('waitForPageLoad', () => { test('should resolve immediately if page is already loaded', async () => { Object.defineProperty(document, 'readyState', { writable: true, configurable: true, value: 'complete' }); + jest.useFakeTimers(); + const resolved = jest.fn(); - const startTime = Date.now(); - await optmlDomUtils.waitForPageLoad(); - const endTime = Date.now(); + optmlDomUtils.waitForPageLoad().then(resolved); - expect(endTime - startTime).toBeLessThan(10); + // Flushes pending promises without letting any time pass. + await jest.advanceTimersByTimeAsync(0); + expect(resolved).toHaveBeenCalled(); + jest.useRealTimers(); }); test('should wait for load event if page not complete', async () => { @@ -329,54 +346,70 @@ describe('optmlDomUtils', () => { test('should fallback to setTimeout if requestIdleCallback not available', async () => { const originalRequestIdleCallback = global.requestIdleCallback; delete global.requestIdleCallback; + jest.useFakeTimers(); + const resolved = jest.fn(); - const startTime = Date.now(); - await optmlDomUtils.waitForIdleTime(); - const endTime = Date.now(); + optmlDomUtils.waitForIdleTime().then(resolved); + + await jest.advanceTimersByTimeAsync(199); + expect(resolved).not.toHaveBeenCalled(); + await jest.advanceTimersByTimeAsync(1); + expect(resolved).toHaveBeenCalled(); + jest.useRealTimers(); - expect(endTime - startTime).toBeGreaterThanOrEqual(200); - // Restore global.requestIdleCallback = originalRequestIdleCallback; }); }); describe('waitForViewportImages', () => { + // Fake timers: wall-clock timing can fire a millisecond early on a busy machine. + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + test('should resolve after delay if page already loaded', async () => { Object.defineProperty(document, 'readyState', { writable: true, configurable: true, value: 'complete' }); + const resolved = jest.fn(); - const startTime = Date.now(); - await optmlDomUtils.waitForViewportImages(100); - const endTime = Date.now(); + optmlDomUtils.waitForViewportImages(100).then(resolved); - expect(endTime - startTime).toBeGreaterThanOrEqual(100); + await jest.advanceTimersByTimeAsync(99); + expect(resolved).not.toHaveBeenCalled(); + await jest.advanceTimersByTimeAsync(1); + expect(resolved).toHaveBeenCalled(); }); test('should wait for load event and then delay', async () => { Object.defineProperty(document, 'readyState', { writable: true, configurable: true, value: 'loading' }); + const resolved = jest.fn(); - const promise = optmlDomUtils.waitForViewportImages(50); - - // Simulate load event - setTimeout(() => { - window.dispatchEvent(new Event('load')); - }, 10); + optmlDomUtils.waitForViewportImages(50).then(resolved); - const startTime = Date.now(); - await promise; - const endTime = Date.now(); + await jest.advanceTimersByTimeAsync(1000); + expect(resolved).not.toHaveBeenCalled(); - expect(endTime - startTime).toBeGreaterThanOrEqual(50); + window.dispatchEvent(new Event('load')); + await jest.advanceTimersByTimeAsync(49); + expect(resolved).not.toHaveBeenCalled(); + await jest.advanceTimersByTimeAsync(1); + expect(resolved).toHaveBeenCalled(); }); test('should use default delay of 1000ms', async () => { Object.defineProperty(document, 'readyState', { writable: true, configurable: true, value: 'complete' }); + const resolved = jest.fn(); - const startTime = Date.now(); - await optmlDomUtils.waitForViewportImages(); - const endTime = Date.now(); + optmlDomUtils.waitForViewportImages().then(resolved); - expect(endTime - startTime).toBeGreaterThanOrEqual(1000); + await jest.advanceTimersByTimeAsync(999); + expect(resolved).not.toHaveBeenCalled(); + await jest.advanceTimersByTimeAsync(1); + expect(resolved).toHaveBeenCalled(); }); }); }); diff --git a/assets/js/modules/__tests__/image-detector.test.js b/assets/js/modules/__tests__/image-detector.test.js index 91aba85d6..9c2841362 100644 --- a/assets/js/modules/__tests__/image-detector.test.js +++ b/assets/js/modules/__tests__/image-detector.test.js @@ -211,6 +211,73 @@ describe('optmlImageDetector', () => { // The observer is created successfully expect(observer).toBeInstanceOf(IntersectionObserver); }); + + test('issue 1216: records a background element under every watcher it matches', () => { + const selectorMap = new Map([ + ['[style*="background-image:url("]', []], + ['[style*="background-image"][style*="url("]', []] + ]); + document.body.innerHTML = '
'; + + const observer = optmlImageDetector.createIntersectionObserver([], selectorMap); + observer.callback([{ isIntersecting: true, target: document.querySelector('div') }]); + + expect(selectorMap.get('[style*="background-image:url("]')).toEqual(['div.hero']); + expect(selectorMap.get('[style*="background-image"][style*="url("]')).toEqual(['div.hero']); + }); + + test.each([ + ['with data-opt-id', ' data-opt-id="77"', [77]], + ['without data-opt-id', '', []] + ])('issue 1216: records an img background %s', (label, idAttribute, expectedImages) => { + const aboveTheFoldImages = []; + const selectorMap = new Map([['[style*="background-image:url("]', []]]); + document.body.innerHTML = ``; + + const observer = optmlImageDetector.createIntersectionObserver(aboveTheFoldImages, selectorMap); + observer.callback([{ isIntersecting: true, target: document.querySelector('img') }]); + + expect(selectorMap.get('[style*="background-image:url("]')).toEqual(['img.bg']); + expect(aboveTheFoldImages).toEqual(expectedImages); + }); + }); + + describe('flushIntersectionObserver', () => { + test('records an element the observer has not reported before it is disconnected', async () => { + const aboveTheFoldImages = []; + const selectorMap = new Map([['[style*="background-image:url("]', []]]); + document.body.innerHTML = ''; + const observer = optmlImageDetector.createIntersectionObserver(aboveTheFoldImages, selectorMap); + observer.takeRecords = jest.fn(() => [{ isIntersecting: true, target: document.querySelector('img') }]); + + await optmlImageDetector.flushIntersectionObserver(observer, aboveTheFoldImages, selectorMap); + + expect(aboveTheFoldImages).toEqual([9]); + expect(selectorMap.get('[style*="background-image:url("]')).toEqual(['img.late']); + }); + + test('records queued entries when no frame is rendered, as in a hidden tab', async () => { + jest.useFakeTimers(); + // Stubbed after the fake timers, which replace requestAnimationFrame too. + const requestAnimationFrameSpy = jest.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 0); + try { + const aboveTheFoldImages = []; + const selectorMap = new Map([['[style*="background-image:url("]', []]]); + document.body.innerHTML = ''; + const observer = optmlImageDetector.createIntersectionObserver(aboveTheFoldImages, selectorMap); + observer.takeRecords = jest.fn(() => [{ isIntersecting: true, target: document.querySelector('img') }]); + + const flushed = optmlImageDetector.flushIntersectionObserver(observer, aboveTheFoldImages, selectorMap); + await jest.advanceTimersByTimeAsync(100); + await flushed; + + expect(aboveTheFoldImages).toEqual([9]); + expect(selectorMap.get('[style*="background-image:url("]')).toEqual(['img.late']); + } finally { + requestAnimationFrameSpy.mockRestore(); + jest.useRealTimers(); + } + }); }); describe('observeOptimoleImages', () => { diff --git a/assets/js/modules/__tests__/main.test.js b/assets/js/modules/__tests__/main.test.js index 55c3f300f..f71b76514 100644 --- a/assets/js/modules/__tests__/main.test.js +++ b/assets/js/modules/__tests__/main.test.js @@ -70,6 +70,7 @@ jest.mock('../lcp.js', () => ({ jest.mock('../image-detector.js', () => ({ optmlImageDetector: { createIntersectionObserver: jest.fn(), + flushIntersectionObserver: jest.fn(), observeOptimoleImages: jest.fn(), detectImageDimensions: jest.fn(), cleanupBackgroundElements: jest.fn() @@ -265,6 +266,30 @@ describe('optmlMain', () => { expect(optmlImageDetector.detectImageDimensions).toHaveBeenCalledWith(mockImages); }); + test('sends dimensions of an image that finishes loading during the profiler waits', async () => { + const { optmlImageDetector: actualImageDetector } = jest.requireActual('../image-detector.js'); + document.body.innerHTML = ''; + const img = document.querySelector('img'); + let naturalWidth = 0; + Object.defineProperty(img, 'naturalWidth', { get: () => naturalWidth }); + Object.defineProperty(img, 'naturalHeight', { get: () => (naturalWidth ? 300 : 0) }); + optmlImageDetector.observeOptimoleImages.mockReturnValue({ + allOptimoleImages: [img], + observedElements: new Map() + }); + optmlImageDetector.detectImageDimensions.mockImplementation(images => actualImageDetector.detectImageDimensions(images)); + optmlSrcsetDetector.detectMissingSrcsets.mockImplementation(async () => { + setTimeout(() => { + naturalWidth = 400; + }, 0); + return { srcset: {}, crop: {} }; + }); + + const result = await optmlMain.runProfiling(); + + expect(result.m).toEqual({ 42: { w: 400, h: 300 } }); + }); + test('should detect missing srcsets', async () => { await optmlMain.runProfiling(); @@ -278,11 +303,89 @@ describe('optmlMain', () => { expect(optmlBackground.processBackgroundSelectors).toHaveBeenCalledWith( ['.hero', '.banner'], - mockObserver + mockObserver, + expect.any(Map) ); expect(optmlBackground.extractBackgroundImageUrls).toHaveBeenCalledWith(['.hero', '.banner']); }); + test('issue 1216: sends above-fold background selectors recorded by the observer with their URLs', async () => { + let observerSelectorMap; + let isLazyloaded = false; + + optmlImageDetector.createIntersectionObserver.mockImplementation((atfImages, selectorMap) => { + observerSelectorMap = selectorMap; + return mockObserver; + }); + + // Simulates the element being lazyloaded and then reported by the observer during the wait. + optmlBackground.processBackgroundSelectors.mockImplementation((selectors, observer, selectorMap = new Map()) => { + selectorMap.set('.hero', []); + setTimeout(() => { + isLazyloaded = true; + observerSelectorMap.get('.hero')?.push('div.hero'); + }, 0); + return { selectorMap, pendingElements: 1 }; + }); + + optmlBackground.extractBackgroundImageUrls.mockImplementation(() => + new Map([['.hero', new Map(isLazyloaded ? [['div.hero', ['hero.jpg']]] : [])]]) + ); + + window.optimoleDataOptimizer.bgSelectors = ['.hero']; + + const result = await optmlMain.runProfiling(); + + expect(result.b).toEqual({ '.hero': { 'div.hero': ['hero.jpg'] } }); + }); + + test('issue 1216: sends at most three background URLs per element and for the LCP', async () => { + const urls = ['1.jpg', '2.jpg', '3.jpg', '4.jpg']; + optmlLcp.detectLcpElement.mockResolvedValue({ + element: null, + imageId: null, + bgSelector: 'div.hero', + bgUrls: urls + }); + optmlBackground.processBackgroundSelectors.mockImplementation((selectors, observer, selectorMap) => { + selectorMap.set('.hero', ['div.hero']); + return { selectorMap, pendingElements: 0 }; + }); + optmlBackground.extractBackgroundImageUrls.mockReturnValue(new Map([['.hero', new Map([['div.hero', urls]])]])); + window.optimoleDataOptimizer.bgSelectors = ['.hero']; + + const result = await optmlMain.runProfiling(); + + expect(result.b['.hero']['div.hero']).toEqual(['1.jpg', '2.jpg', '3.jpg']); + expect(result.l.u).toEqual(['1.jpg', '2.jpg', '3.jpg']); + }); + + test('issue 1216: sends at most 100 above-fold selectors per watcher', async () => { + const specificSelectors = Array.from({ length: 101 }, (value, index) => `div.tile:nth-of-type(${index + 1})`); + optmlBackground.processBackgroundSelectors.mockImplementation((selectors, observer, selectorMap) => { + selectorMap.set('.tile', specificSelectors); + return { selectorMap, pendingElements: 0 }; + }); + window.optimoleDataOptimizer.bgSelectors = ['.tile']; + + const result = await optmlMain.runProfiling(); + + expect(Object.keys(result.b['.tile'])).toEqual(specificSelectors.slice(0, 100)); + }); + + test('issue 1216: sends at most 100 watchers', async () => { + const watchers = Array.from({ length: 101 }, (value, index) => `.bg-${index}`); + optmlBackground.processBackgroundSelectors.mockImplementation((selectors, observer, selectorMap) => { + watchers.forEach(watcher => selectorMap.set(watcher, [])); + return { selectorMap, pendingElements: 0 }; + }); + window.optimoleDataOptimizer.bgSelectors = watchers; + + const result = await optmlMain.runProfiling(); + + expect(Object.keys(result.b)).toEqual(watchers.slice(0, 100)); + }); + test('should send data to API when images found', async () => { // Create a real image element and add to DOM document.body.innerHTML = ''; @@ -332,6 +435,22 @@ describe('optmlMain', () => { ); }); + test('records the observer entries still queued before disconnecting it', async () => { + const calls = []; + let observerArgs; + optmlImageDetector.createIntersectionObserver.mockImplementation((atfImages, selectorMap) => { + observerArgs = [atfImages, selectorMap]; + return mockObserver; + }); + optmlImageDetector.flushIntersectionObserver.mockImplementation(() => calls.push('flush')); + mockObserver.disconnect.mockImplementation(() => calls.push('disconnect')); + + await optmlMain.runProfiling(); + + expect(optmlImageDetector.flushIntersectionObserver).toHaveBeenCalledWith(mockObserver, ...observerArgs); + expect(calls).toEqual(['flush', 'disconnect']); + }); + test('should clean up event listeners after profiling', async () => { await optmlMain.runProfiling(); @@ -445,11 +564,9 @@ describe('optmlMain', () => { }); // Setup background - const selectorMap = new Map(); - selectorMap.set('.hero', ['div.hero']); - optmlBackground.processBackgroundSelectors.mockReturnValue({ - selectorMap, - pendingElements: 0 + optmlBackground.processBackgroundSelectors.mockImplementation((selectors, observer, selectorMap) => { + selectorMap.set('.hero', ['div.hero']); + return { selectorMap, pendingElements: 0 }; }); const bgUrls = new Map(); diff --git a/assets/js/modules/background.js b/assets/js/modules/background.js index e77a9635e..c7470cac9 100644 --- a/assets/js/modules/background.js +++ b/assets/js/modules/background.js @@ -19,31 +19,45 @@ export const optmlBackground = { * @returns {number} Number of elements waiting for lazy load */ setupBackgroundImageObservation: function(elements, selector, selectorMap, observer) { + /** + * Observe a background element, re-observing so an element already observed as an Optimole image + * gets a fresh callback (its first one ran before it was marked as a background) + * @param {Element} element - Background element to observe + * @returns {void} + */ + const observeBackground = element => { + observer.unobserve(element); + observer.observe(element); + }; + + // Elements still waiting for the lazyload class + const elementsToWatch = new Set(); + // Create a single shared observer for all elements + // Only class changes are delivered (see attributeFilter below) const classObserver = new MutationObserver((mutations) => { - for (const mutation of mutations) { - if (mutation.type === 'attributes' && mutation.attributeName === 'class') { - const element = mutation.target; - - // Check if element now has the required class and a background image - if (element.classList.contains('optml-bg-lazyloaded') && - optmlDomUtils.hasBackgroundImage(element)) { - // Start observing for visibility - observer.observe(element); - - // Stop watching for class changes on this element - classObserver.disconnect(element); - - const specificSelector = element.getAttribute('data-optml-specific-selector'); - optmlLogger.info(`Background element "${specificSelector}" is now observable`); - } + mutations.forEach(({ target: element }) => { + // Check if element now has the required class and a background image + if (!elementsToWatch.has(element) || + !element.classList.contains('optml-bg-lazyloaded') || + !optmlDomUtils.hasBackgroundImage(element)) { + return; } - } + + // Start observing for visibility + observeBackground(element); + + // disconnect() stops watching every element, so wait until none is pending + elementsToWatch.delete(element); + if (elementsToWatch.size === 0) { + classObserver.disconnect(); + } + + const specificSelector = element.getAttribute('data-optml-specific-selector'); + optmlLogger.info(`Background element "${specificSelector}" is now observable`); + }); }); - // Process all elements at once - const elementsToWatch = []; - elements.forEach(element => { // Generate a specific selector for this element const specificSelector = optmlDomUtils.getUniqueSelector(element); @@ -55,15 +69,15 @@ export const optmlBackground = { // If already lazyloaded with background image, observe immediately if (element.classList.contains('optml-bg-lazyloaded') && optmlDomUtils.hasBackgroundImage(element)) { - observer.observe(element); + observeBackground(element); } else { // Otherwise, add to the list to watch for class changes - elementsToWatch.push(element); + elementsToWatch.add(element); } }); // Set up observation for class changes only on elements that need it - if (elementsToWatch.length > 0) { + if (elementsToWatch.size > 0) { elementsToWatch.forEach(element => { classObserver.observe(element, { attributes: true, attributeFilter: ['class'] }); }); @@ -75,7 +89,7 @@ export const optmlBackground = { }, 5000); } - return elementsToWatch.length; + return elementsToWatch.size; }, /** @@ -127,10 +141,10 @@ export const optmlBackground = { * Process background selectors and setup observation * @param {Array} bgSelectors - Array of CSS selectors * @param {IntersectionObserver} observer - Intersection observer instance - * @returns {Object} Object containing selectorMap and pendingElements count + * @param {Map>} [selectorMap] - Map the observer records above-fold selectors into; must be the same instance passed to the observer + * @returns {{selectorMap: Map>, pendingElements: number}} Object containing selectorMap and pendingElements count */ - processBackgroundSelectors: function(bgSelectors, observer) { - const selectorMap = new Map(); + processBackgroundSelectors: function(bgSelectors, observer, selectorMap = new Map()) { let pendingElements = 0; if (!bgSelectors || !Array.isArray(bgSelectors) || bgSelectors.length === 0) { diff --git a/assets/js/modules/dom-utils.js b/assets/js/modules/dom-utils.js index e7265438c..b4ed9d816 100644 --- a/assets/js/modules/dom-utils.js +++ b/assets/js/modules/dom-utils.js @@ -36,18 +36,13 @@ export const optmlDomUtils = { const tag = element.tagName.toLowerCase(); - // Optimize class name processing let className = ''; if (element.className && typeof element.className === 'string') { - // Only process if needed - if (element.className.includes('optml-bg-lazyloaded')) { - className = '.' + element.className.trim() - .split(/\s+/) - .filter(cls => cls !== 'optml-bg-lazyloaded') - .join('.'); - } else { - // Avoid unnecessary split/filter/join when no filtering needed - className = '.' + element.className.trim().replace(/\s+/g, '.'); + const classes = element.className.trim() + .split(/\s+/) + .filter(cls => cls && cls !== 'optml-bg-lazyloaded'); + if (classes.length > 0) { + className = '.' + classes.join('.'); } } diff --git a/assets/js/modules/image-detector.js b/assets/js/modules/image-detector.js index cb81f329c..675180e85 100644 --- a/assets/js/modules/image-detector.js +++ b/assets/js/modules/image-detector.js @@ -76,43 +76,83 @@ export const optmlImageDetector = { /** * Setup intersection observer for image detection * @param {Array} aboveTheFoldImages - Array to store above-fold image IDs - * @param {Map} selectorMap - Map for background selectors + * @param {Map>} selectorMap - Map of base selector to above-fold specific selectors * @returns {IntersectionObserver} Configured intersection observer */ createIntersectionObserver: function(aboveTheFoldImages, selectorMap) { return new IntersectionObserver(entries => { - entries.forEach(entry => { - if (entry.isIntersecting) { - const element = entry.target; - - // Handle img elements with data-opt-id - if (element.tagName === 'IMG') { - const id = parseInt(element.getAttribute('data-opt-id'), 10); - if (!isNaN(id) && !aboveTheFoldImages.includes(id)) { - aboveTheFoldImages.push(id); - } - } - // Handle background image elements - else if (element.hasAttribute('data-optml-bg-selector')) { - const baseSelector = element.getAttribute('data-optml-bg-selector'); - const specificSelector = element.getAttribute('data-optml-specific-selector'); - - if (baseSelector && specificSelector && selectorMap.has(baseSelector)) { - // Add this specific selector to the above-fold list for this base selector - const aboveTheFoldSelectors = selectorMap.get(baseSelector); - if (!aboveTheFoldSelectors.includes(specificSelector)) { - aboveTheFoldSelectors.push(specificSelector); - optmlLogger.info(`Element with selector "${specificSelector}" is above the fold`); - } - } - } - } - }); + this.recordIntersections(entries, aboveTheFoldImages, selectorMap); }, { threshold: 0.1 // Consider element visible when 10% is in viewport }); }, + /** + * Record the above-fold images and background elements of intersection entries + * @param {Array} entries - Entries reported by the observer + * @param {Array} aboveTheFoldImages - Array to store above-fold image IDs + * @param {Map>} selectorMap - Map of base selector to above-fold specific selectors + * @returns {void} + */ + recordIntersections: function(entries, aboveTheFoldImages, selectorMap) { + entries.forEach(entry => { + if (!entry.isIntersecting) { + return; + } + const element = entry.target; + + // Handle img elements with data-opt-id + if (element.tagName === 'IMG') { + const id = parseInt(element.getAttribute('data-opt-id'), 10); + if (!isNaN(id) && !aboveTheFoldImages.includes(id)) { + aboveTheFoldImages.push(id); + } + } + + // An img can also carry a background image, so this is checked independently. + if (element.hasAttribute('data-optml-bg-selector')) { + this.recordAboveFoldBackground(element, selectorMap); + } + }); + }, + + /** + * Record elements observed shortly before the observer is disconnected + * @param {IntersectionObserver} observer - Observer created by createIntersectionObserver + * @param {Array} aboveTheFoldImages - Array to store above-fold image IDs + * @param {Map>} selectorMap - Map of base selector to above-fold specific selectors + * @returns {Promise} Resolves once the queued entries are recorded + */ + flushIntersectionObserver: async function(observer, aboveTheFoldImages, selectorMap) { + // A new observation is computed only at the next rendering; hidden tabs render no frames, hence the timeout. + await Promise.race([ + new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))), + new Promise(resolve => setTimeout(resolve, 100)) + ]); + this.recordIntersections(observer.takeRecords(), aboveTheFoldImages, selectorMap); + }, + + /** + * Record a background element under every base selector it matches + * @param {Element} element - Above-the-fold background element + * @param {Map>} selectorMap - Map of base selector to above-fold specific selectors + * @returns {void} + */ + recordAboveFoldBackground: function(element, selectorMap) { + const specificSelector = element.getAttribute('data-optml-specific-selector'); + if (!specificSelector) { + return; + } + + // An element can match several watchers; each one needs it listed or the server hides it. + selectorMap.forEach((aboveTheFoldSelectors, baseSelector) => { + if (element.matches(baseSelector) && !aboveTheFoldSelectors.includes(specificSelector)) { + aboveTheFoldSelectors.push(specificSelector); + optmlLogger.info(`Element with selector "${specificSelector}" is above the fold`); + } + }); + }, + /** * Observe all images with data-opt-id attributes * @param {IntersectionObserver} observer - Intersection observer instance diff --git a/assets/js/modules/main.js b/assets/js/modules/main.js index ad0c7fb68..48acc6513 100644 --- a/assets/js/modules/main.js +++ b/assets/js/modules/main.js @@ -13,6 +13,11 @@ import { optmlLcp } from './lcp.js'; import { optmlImageDetector } from './image-detector.js'; import { optmlSrcsetDetector } from './srcset-detector.js'; +// The optimizations endpoint rejects the whole payload when these limits are exceeded. +const MAX_BG_URLS_PER_ELEMENT = 3; +const MAX_ABOVE_FOLD_SELECTORS_PER_WATCHER = 100; +const MAX_BG_WATCHERS = 100; + /** * Main detection functionality */ @@ -107,17 +112,12 @@ export const optmlMain = { const aboveTheFoldImages = []; // Create intersection observer - let selectorMap = new Map(); + const selectorMap = new Map(); const observer = optmlImageDetector.createIntersectionObserver(aboveTheFoldImages, selectorMap); // Observe Optimole images const { allOptimoleImages } = optmlImageDetector.observeOptimoleImages(observer); - // Detect images with missing dimensions - const imageDimensionsData = optmlImageDetector.detectImageDimensions(allOptimoleImages); - - optmlLogger.info('Images with missing dimensions found:', Object.keys(imageDimensionsData).length); - // Detect images requiring srcset variations (non-lazyload images) const srcsetResult = await optmlSrcsetDetector.detectMissingSrcsets(); const srcsetData = srcsetResult.srcset; @@ -131,22 +131,29 @@ export const optmlMain = { let pendingElements = 0; if (bgSelectors && Array.isArray(bgSelectors) && bgSelectors.length > 0) { - const backgroundResult = optmlBackground.processBackgroundSelectors(bgSelectors, observer); - selectorMap = backgroundResult.selectorMap; + const backgroundResult = optmlBackground.processBackgroundSelectors(bgSelectors, observer, selectorMap); pendingElements = backgroundResult.pendingElements; - // Extract background image URLs - bgImageUrls = optmlBackground.extractBackgroundImageUrls(bgSelectors); - // Adjust wait time based on whether we have pending elements const waitTime = pendingElements > 0 ? 600 : 300; optmlLogger.info(`Waiting ${waitTime}ms for ${pendingElements} pending background elements`); await new Promise(resolve => setTimeout(resolve, waitTime)); + + // Extract after the wait so elements lazyloaded during it are included. + bgImageUrls = optmlBackground.extractBackgroundImageUrls(bgSelectors); } else { // Standard wait time if no background selectors await new Promise(resolve => setTimeout(resolve, 300)); } + // Elements lazyloaded at the end of the wait are not reported yet. + await optmlImageDetector.flushIntersectionObserver(observer, aboveTheFoldImages, selectorMap); + + // Read after the waits so images that finished loading during them have natural dimensions. + const imageDimensionsData = optmlImageDetector.detectImageDimensions(allOptimoleImages); + + optmlLogger.info('Images with missing dimensions found:', Object.keys(imageDimensionsData).length); + // Disconnect observer and clean up event listeners observer.disconnect(); window.removeEventListener('resize', resizeHandler); @@ -185,7 +192,7 @@ export const optmlMain = { l: { i: lcpData.imageId, s: lcpData.bgSelector, - u: lcpData.bgUrls + u: lcpData.bgUrls ? lcpData.bgUrls.slice(0, MAX_BG_URLS_PER_ELEMENT) : lcpData.bgUrls }, m: imageDimensionsData, // m for missing dimensions s: srcsetData, // s for srcset data @@ -221,20 +228,20 @@ export const optmlMain = { const processedBgSelectors = {}; // Process each selector that's present on the page - selectorMap.forEach((specificSelectors, baseSelector) => { + Array.from(selectorMap).slice(0, MAX_BG_WATCHERS).forEach(([baseSelector, specificSelectors]) => { // Initialize the object for this base selector processedBgSelectors[baseSelector] = {}; // For each specific selector, add its URLs if available - specificSelectors.forEach(specificSelector => { + specificSelectors.slice(0, MAX_ABOVE_FOLD_SELECTORS_PER_WATCHER).forEach(specificSelector => { // First, add the selector to indicate it's above the fold processedBgSelectors[baseSelector][specificSelector] = null; // Then, if we have URLs for this selector, add them if (bgImageUrls.has(baseSelector) && bgImageUrls.get(baseSelector).has(specificSelector)) { - processedBgSelectors[baseSelector][specificSelector] = - bgImageUrls.get(baseSelector).get(specificSelector); + processedBgSelectors[baseSelector][specificSelector] = + bgImageUrls.get(baseSelector).get(specificSelector).slice(0, MAX_BG_URLS_PER_ELEMENT); } }); }); diff --git a/inc/manager.php b/inc/manager.php index b55c2de33..3adb2f2f2 100644 --- a/inc/manager.php +++ b/inc/manager.php @@ -564,7 +564,7 @@ public function replace_content( $html, $partial = false ) { } $marker = Lazyload::get_marker(); - if ( ! empty( $personalized_bg_css ) && ( $start_pos = strpos( $html, $marker ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found + if ( null !== $personalized_bg_css && ( $start_pos = strpos( $html, $marker ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found // We replace the general bg css with the personalized one. if ( ( $end_pos = strpos( $html, $marker, $start_pos + strlen( $marker ) ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found $html = substr_replace( diff --git a/inc/rest.php b/inc/rest.php index 50e086529..c719d432a 100644 --- a/inc/rest.php +++ b/inc/rest.php @@ -9,6 +9,7 @@ use Optimole\Sdk\Resource\ImageProperty\ResizeTypeProperty; use Optimole\Sdk\ValueObject\Position; +use OptimoleWP\BgOptimizer\Lazyload; use OptimoleWP\PageProfiler\Profile; /** @@ -1013,7 +1014,7 @@ public function optimizations( WP_REST_Request $request ) { // save just the first 6 images, see https://github.com/Codeinwp/optimole-service/issues/1588#issuecomment-3357110865 $above_fold_images = array_slice( $above_fold_images, 0, 6 ); $above_fold_images = array_values( array_map( 'intval', array_filter( $above_fold_images, 'is_numeric' ) ) ); - if ( count( $bg_selectors ) > 100 ) { + if ( count( $bg_selectors ) > Lazyload::MAX_WATCHERS ) { return $this->response( 'Background selectors limit exceeded', 'error' ); } if ( $url === Profile::PLACEHOLDER ) { @@ -1026,7 +1027,7 @@ public function optimizations( WP_REST_Request $request ) { if ( ! in_array( $selector, $current_selectors, true ) ) { return $this->response( 'Invalid background selector', 'error' ); } - if ( count( $above_fold_bg_selectors ) > 100 ) { + if ( count( $above_fold_bg_selectors ) > Lazyload::MAX_ABOVE_FOLD_SELECTORS ) { return $this->response( 'Above fold background selectors limit exceeded', 'error' ); } $selector = strip_tags( $selector ); diff --git a/inc/v2/BgOptimizer/Lazyload.php b/inc/v2/BgOptimizer/Lazyload.php index 0c57a65e2..15f8081f1 100644 --- a/inc/v2/BgOptimizer/Lazyload.php +++ b/inc/v2/BgOptimizer/Lazyload.php @@ -18,6 +18,21 @@ class Lazyload { */ const SAFE_SELECTOR_PATTERN = '/^(?:[\w\-#. >\x{00A0}-\x{10FFFF}]|:nth-of-type\(\d+\))+$/u'; + /** + * Most watchers the profiler reports per device; the frontend cuts the rest. + */ + const MAX_WATCHERS = 100; + + /** + * Most above-fold selectors the profiler reports per watcher; the frontend cuts the rest. + */ + const MAX_ABOVE_FOLD_SELECTORS = 100; + + /** + * Widest viewport in px the profiler counts as mobile (MOBILE_BREAKPOINT in device.js). + */ + private const DEVICE_BREAKPOINT = 600; + /** * Check whether a client-reported selector is a plain selector safe to embed in the stylesheet as-is. * @@ -46,9 +61,9 @@ public static function get_marker(): string { /** * Get the current personalized CSS for lazy loading. * - * @return string The personalized CSS. + * @return string|null The personalized CSS, or null when the general CSS must stay. */ - public static function get_current_personalized_css() { + public static function get_current_personalized_css(): ?string { return self::get_personalized_css( Profile::get_current_profile_data() ); } /** @@ -56,9 +71,9 @@ public static function get_current_personalized_css() { * * @param array $data Profile data. * - * @return string The personalized CSS. + * @return string|null The personalized CSS ('' hides nothing), or null when every device was voided and the general CSS must stay. */ - public static function get_personalized_css( $data ) { + public static function get_personalized_css( $data ): ?string { $lazyload_selectors = array_values( Optml_Lazyload_Replacer::get_background_lazyload_selectors() ); $lazyload_selectors = array_fill_keys( $lazyload_selectors, true ); $css_selectors = []; @@ -94,35 +109,27 @@ public static function get_personalized_css( $data ) { Links::add_link( [ 'url' => $url, 'priority' => 'high' ] ); } - $hide_rule = ' { background-image: none !important; }'; - $mobile = $css_selectors[ Profile::DEVICE_TYPE_MOBILE ]; - $desktop = $css_selectors[ Profile::DEVICE_TYPE_DESKTOP ]; - - // Keep the surviving rule scoped when the other device was voided. - if ( $tainted[ Profile::DEVICE_TYPE_MOBILE ] !== $tainted[ Profile::DEVICE_TYPE_DESKTOP ] ) { - if ( $tainted[ Profile::DEVICE_TYPE_MOBILE ] ) { - return empty( $desktop ) ? '' : '@media (min-width: 600px) { ' . implode( ',', $desktop ) . $hide_rule . ' }'; - } - return empty( $mobile ) ? '' : '@media (max-width: 600px) { ' . implode( ',', $mobile ) . $hide_rule . ' }'; + if ( ! in_array( false, $tainted, true ) ) { + return null; } - $mobile_selectors = implode( ',', $mobile ); - $desktop_selectors = implode( ',', $desktop ); + $hide_rule = ' { background-image: none !important; }'; + $mobile_selectors = implode( ',', $css_selectors[ Profile::DEVICE_TYPE_MOBILE ] ); + $desktop_selectors = implode( ',', $css_selectors[ Profile::DEVICE_TYPE_DESKTOP ] ); if ( $mobile_selectors === $desktop_selectors ) { - return empty( $mobile_selectors ) ? '' : $mobile_selectors . $hide_rule; + return $mobile_selectors === '' ? '' : $mobile_selectors . $hide_rule; } - // if any of those are empty, return the other one - if ( empty( $mobile_selectors ) ) { - return $desktop_selectors . $hide_rule; + + // A device without selectors hides nothing on purpose (voided or capped), so the other rule stays in its media query. + $media_queries = []; + if ( $mobile_selectors !== '' ) { + $media_queries[] = '@media (max-width: ' . self::DEVICE_BREAKPOINT . 'px) { ' . $mobile_selectors . $hide_rule . ' }'; } - if ( empty( $desktop_selectors ) ) { - return $mobile_selectors . $hide_rule; + if ( $desktop_selectors !== '' ) { + $media_queries[] = '@media (min-width: ' . ( self::DEVICE_BREAKPOINT + 1 ) . 'px) { ' . $desktop_selectors . $hide_rule . ' }'; } - - // generate media query for desktop and mobile - $media_query = '@media (max-width: 600px) { ' . $mobile_selectors . $hide_rule . ' } @media (min-width: 600px) { ' . $desktop_selectors . $hide_rule . ' }'; - return $media_query; + return implode( ' ', $media_queries ); } /** * Build the background-hide selectors for one device. @@ -139,15 +146,25 @@ private static function collect_device_selectors( array $personalized_selectors, if ( ! isset( $lazyload_selectors[ $selector ] ) ) { continue; } - if ( empty( $above_fold_selectors ) ) { - $css_selectors[] = 'html ' . strip_tags( $selector ) . ':not(.optml-bg-lazyloaded)'; + // A full list may have been cut, so hiding the watcher could delay unlisted above-fold elements. + if ( count( $above_fold_selectors ) >= self::MAX_ABOVE_FOLD_SELECTORS ) { continue; } + // One rule per watcher: a separate rule per element would still hide the watcher's other above-fold elements. + $exemptions = ''; foreach ( $above_fold_selectors as $above_fold_selector => $bg_urls ) { if ( ! self::is_safe_selector( $above_fold_selector ) ) { return null; } - $css_selectors[] = 'html ' . strip_tags( $selector ) . ':not(' . $above_fold_selector . '):not(.optml-bg-lazyloaded)'; + $exemptions .= ':not(' . $above_fold_selector . ')'; + } + $css_selectors[] = 'html ' . strip_tags( $selector ) . $exemptions . ':not(.optml-bg-lazyloaded)'; + } + + // This CSS replaces the generic one, so unlisted watchers keep it unless the watcher list may have been cut. + if ( count( $personalized_selectors ) < self::MAX_WATCHERS ) { + foreach ( array_keys( array_diff_key( $lazyload_selectors, $personalized_selectors ) ) as $selector ) { + $css_selectors[] = 'html ' . strip_tags( $selector ) . ':not(.optml-bg-lazyloaded)'; } } diff --git a/tests/test-bg-selector.php b/tests/test-bg-selector.php index f03680e2e..f1cb2a3bc 100644 --- a/tests/test-bg-selector.php +++ b/tests/test-bg-selector.php @@ -127,9 +127,153 @@ public function test_personalized_css_drops_injected_selectors(): void { ] ); - $this->assertStringNotContainsString( 'background:red', $css ); - $this->assertStringNotContainsString( self::PAYLOAD, $css ); - $this->assertSame( '', $css ); + $this->assertNull( $css ); + } + + /** + * Issue 1216: all above-fold elements of a watcher are exempted in one rule, since a separate + * rule per element would still hide the other elements. + */ + public function test_personalized_css_exempts_all_above_fold_elements_in_one_rule(): void { + $device_data = [ 'bg' => [ self::WATCHER => [ '#hero-a' => [], '#hero-b' => [] ] ] ]; + + $css = Lazyload::get_personalized_css( + [ + Profile::DEVICE_TYPE_MOBILE => $device_data, + Profile::DEVICE_TYPE_DESKTOP => $device_data, + ] + ); + + $this->assertStringContainsString( 'html ' . self::WATCHER . ':not(#hero-a):not(#hero-b):not(.optml-bg-lazyloaded)', $css ); + $this->assertStringNotContainsString( 'html ' . self::WATCHER . ':not(#hero-a):not(.optml-bg-lazyloaded)', $css ); + $this->assertStringNotContainsString( 'html ' . self::WATCHER . ':not(#hero-b):not(.optml-bg-lazyloaded)', $css ); + } + + /** + * A watcher the profile does not list keeps its generic hide rule while the watcher list is below the cap. + */ + public function test_personalized_css_keeps_generic_rule_for_unlisted_watchers(): void { + $device_data = [ 'bg' => [ '.bg-0' => [ '#hero' => [] ] ] ]; + + $css = $this->get_css_with_watchers( 1, $device_data ); + + $this->assertStringContainsString( 'html ' . self::WATCHER . ':not(.optml-bg-lazyloaded)', $css ); + $this->assertStringContainsString( 'html .bg-0:not(#hero):not(.optml-bg-lazyloaded)', $css ); + } + + /** + * When the profile lists the maximum number of watchers, the client may have cut others, so unlisted + * watchers get no hide rule. + */ + public function test_personalized_css_skips_unlisted_watchers_when_watcher_list_is_full(): void { + $watchers = array_map( + static function ( int $index ): string { + return '.bg-' . $index; + }, + range( 0, Lazyload::MAX_WATCHERS ) + ); + $bg = array_fill_keys( array_slice( $watchers, 0, Lazyload::MAX_WATCHERS ), [] ); + $bg['.bg-0'] = [ '#hero' => [] ]; + + $css = $this->get_css_with_watchers( Lazyload::MAX_WATCHERS + 1, [ 'bg' => $bg ] ); + + $this->assertStringNotContainsString( 'html .bg-' . Lazyload::MAX_WATCHERS . ':', $css ); + $this->assertStringNotContainsString( 'html ' . self::WATCHER . ':', $css ); + $this->assertStringContainsString( 'html .bg-0:not(#hero):not(.optml-bg-lazyloaded)', $css ); + $this->assertStringContainsString( 'html .bg-1:not(.optml-bg-lazyloaded)', $css ); + } + + /** + * A watcher whose above-fold list hit the cap may be missing above-fold elements, so it gets no hide rule. + */ + public function test_personalized_css_skips_watcher_with_full_above_fold_list(): void { + $above_fold = []; + foreach ( range( 1, Lazyload::MAX_ABOVE_FOLD_SELECTORS ) as $index ) { + $above_fold[ '#hero-' . $index ] = []; + } + $device_data = [ + 'bg' => [ + '.bg-0' => $above_fold, + '.bg-1' => array_slice( $above_fold, 0, Lazyload::MAX_ABOVE_FOLD_SELECTORS - 1 ), + ], + ]; + + $css = $this->get_css_with_watchers( 2, $device_data ); + + $this->assertStringNotContainsString( 'html .bg-0:', $css ); + $this->assertStringContainsString( 'html .bg-1:not(#hero-1)', $css ); + } + + /** + * When one device's watcher hit the above-fold cap, the other device's hide rule stays in its media query. + */ + public function test_personalized_css_scopes_other_device_rule_when_one_device_is_capped(): void { + $above_fold = []; + foreach ( range( 1, Lazyload::MAX_ABOVE_FOLD_SELECTORS ) as $index ) { + $above_fold[ '#hero-' . $index ] = []; + } + $only_watcher = static function (): array { + return [ '.bg-0' ]; + }; + add_filter( 'optml_lazyload_bg_selectors', $only_watcher ); + $this->reset_background_selectors(); + + $css = Lazyload::get_personalized_css( + [ + Profile::DEVICE_TYPE_MOBILE => [ 'bg' => [ '.bg-0' => $above_fold ] ], + Profile::DEVICE_TYPE_DESKTOP => [ 'bg' => [ '.bg-0' => array_slice( $above_fold, 0, Lazyload::MAX_ABOVE_FOLD_SELECTORS - 1 ) ] ], + ] + ); + remove_filter( 'optml_lazyload_bg_selectors', $only_watcher ); + + $this->assertIsString( $css ); + $this->assertStringStartsWith( '@media (min-width: 601px) { html .bg-0:not(#hero-1)', $css ); + $this->assertStringNotContainsString( 'max-width', $css ); + } + + /** + * The profiler counts a 600px viewport as mobile, so only the mobile rule applies there. + */ + public function test_personalized_css_device_media_queries_do_not_overlap(): void { + $css = Lazyload::get_personalized_css( + [ + Profile::DEVICE_TYPE_MOBILE => [ 'bg' => [ self::WATCHER => [ '#hero-mobile' => [] ] ] ], + Profile::DEVICE_TYPE_DESKTOP => [ 'bg' => [ self::WATCHER => [ '#hero-desktop' => [] ] ] ], + ] + ); + + $this->assertIsString( $css ); + $this->assertStringContainsString( '@media (max-width: 600px) { html ' . self::WATCHER . ':not(#hero-mobile)', $css ); + $this->assertStringContainsString( '@media (min-width: 601px) { html ' . self::WATCHER . ':not(#hero-desktop)', $css ); + } + + /** + * Build the personalized CSS for both devices with extra watchers .bg-0 … .bg-{count-1} registered. + * + * @param int $count Number of extra watchers to register. + * @param array $device_data Profile data used for both devices. + * + * @return string Personalized CSS. + */ + private function get_css_with_watchers( int $count, array $device_data ): string { + $add_watchers = static function ( array $selectors ) use ( $count ): array { + foreach ( range( 0, $count - 1 ) as $index ) { + $selectors[] = '.bg-' . $index; + } + return $selectors; + }; + add_filter( 'optml_lazyload_bg_selectors', $add_watchers ); + $this->reset_background_selectors(); + + $css = Lazyload::get_personalized_css( + [ + Profile::DEVICE_TYPE_MOBILE => $device_data, + Profile::DEVICE_TYPE_DESKTOP => $device_data, + ] + ); + remove_filter( 'optml_lazyload_bg_selectors', $add_watchers ); + + return $css; } /** @@ -151,8 +295,7 @@ public function test_personalized_css_drops_injected_lcp_selector(): void { ] ); - $this->assertStringNotContainsString( 'background:red', $css ); - $this->assertSame( '', $css ); + $this->assertNull( $css ); } /** @@ -175,8 +318,7 @@ public function test_personalized_css_drops_rule_when_any_selector_unsafe(): voi ] ); - $this->assertStringNotContainsString( 'background:red', $css ); - $this->assertSame( '', $css ); + $this->assertNull( $css ); } /** @@ -200,7 +342,7 @@ public function test_personalized_css_scopes_surviving_device_to_media_query(): $this->assertStringNotContainsString( 'background:red', $css ); $this->assertStringNotContainsString( self::PAYLOAD, $css ); // The surviving desktop rule must stay desktop-scoped and not apply on phones. - $this->assertStringStartsWith( '@media (min-width: 600px) {', $css ); + $this->assertStringStartsWith( '@media (min-width: 601px) {', $css ); $this->assertStringNotContainsString( '@media (max-width: 600px)', $css ); // The safe above-fold and LCP selectors are still rendered (the gating must not over-reject them). $this->assertStringContainsString( ':not(#hero):not(.optml-bg-lazyloaded)', $css ); diff --git a/tests/test-viewport-bg-css.php b/tests/test-viewport-bg-css.php index ea3140999..3932f20c3 100644 --- a/tests/test-viewport-bg-css.php +++ b/tests/test-viewport-bg-css.php @@ -50,7 +50,7 @@ public function setUp(): void { add_filter( 'optml_page_profile_id', [ self::class, 'profile_id' ] ); foreach ( [ Profile::DEVICE_TYPE_MOBILE, Profile::DEVICE_TYPE_DESKTOP ] as $device ) { - Optml_Manager::instance()->page_profiler->store( self::PROFILE_ID, $device, [], [ self::WATCHER => [] ] ); + Optml_Manager::instance()->page_profiler->store( self::PROFILE_ID, $device, [], [ self::WATCHER => [ '#hero' => [] ] ] ); } } @@ -98,8 +98,11 @@ private function comment(): string { return 'x'; } + /** + * A rule only the personalized CSS contains: the generic CSS has no above-fold exemption. + */ private function personalized_rule(): string { - return 'html ' . self::WATCHER . ':not(.optml-bg-lazyloaded) { background-image: none !important; }'; + return 'html ' . self::WATCHER . ':not(#hero):not(.optml-bg-lazyloaded)'; } public function test_marker_carries_a_random_token(): void { @@ -211,4 +214,36 @@ public function test_marker_printed_before_the_plugin_style_is_not_paired_with_i $this->assertStringContainsString( $title, $replaced ); $this->assertStringContainsString( $this->personalized_rule(), $replaced ); } + + public function test_general_css_is_removed_when_every_device_hides_nothing(): void { + $only_watcher = static function (): array { + return [ self::WATCHER ]; + }; + add_filter( 'optml_lazyload_bg_selectors', $only_watcher ); + $this->reset_background_selectors(); + $above_fold = []; + foreach ( range( 1, Lazyload::MAX_ABOVE_FOLD_SELECTORS ) as $index ) { + $above_fold[ '#hero-' . $index ] = []; + } + foreach ( [ Profile::DEVICE_TYPE_MOBILE, Profile::DEVICE_TYPE_DESKTOP ] as $device ) { + Optml_Manager::instance()->page_profiler->store( self::PROFILE_ID, $device, [], [ self::WATCHER => $above_fold ] ); + } + $html = '' . $this->plugin_style() . '

Body.

'; + + $replaced = Optml_Manager::instance()->replace_content( $html ); + remove_filter( 'optml_lazyload_bg_selectors', $only_watcher ); + $this->reset_background_selectors(); + + $this->assertStringContainsString( 'optml_no_js', $replaced ); + $this->assertStringNotContainsString( 'html ' . self::WATCHER . ':not(.optml-bg-lazyloaded)', $replaced ); + } + + /** + * Reset the cached background lazyload selectors. + */ + private function reset_background_selectors(): void { + $property = new ReflectionProperty( Optml_Lazyload_Replacer::class, 'background_lazyload_selectors' ); + $property->setAccessible( true ); + $property->setValue( null, null ); + } }