From 56209c98a4c05b6e27f13b5b37c7b739d0563692 Mon Sep 17 00:00:00 2001 From: girishpanchal30 Date: Mon, 16 Nov 2026 11:12:23 +0530 Subject: [PATCH 01/13] fix: store above-fold background images --- .../js/modules/__tests__/background.test.js | 11 +++++ assets/js/modules/__tests__/main.test.js | 41 ++++++++++++++++--- assets/js/modules/background.js | 6 +-- assets/js/modules/main.js | 11 +++-- 4 files changed, 54 insertions(+), 15 deletions(-) diff --git a/assets/js/modules/__tests__/background.test.js b/assets/js/modules/__tests__/background.test.js index 9f10247d0..11fb0b930 100644 --- a/assets/js/modules/__tests__/background.test.js +++ b/assets/js/modules/__tests__/background.test.js @@ -294,6 +294,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__/main.test.js b/assets/js/modules/__tests__/main.test.js index 55c3f300f..e477ab791 100644 --- a/assets/js/modules/__tests__/main.test.js +++ b/assets/js/modules/__tests__/main.test.js @@ -278,11 +278,42 @@ 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('should send data to API when images found', async () => { // Create a real image element and add to DOM document.body.innerHTML = ''; @@ -445,11 +476,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..6b956e6f6 100644 --- a/assets/js/modules/background.js +++ b/assets/js/modules/background.js @@ -127,10 +127,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/main.js b/assets/js/modules/main.js index ad0c7fb68..1eb1f5554 100644 --- a/assets/js/modules/main.js +++ b/assets/js/modules/main.js @@ -107,7 +107,7 @@ 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 @@ -131,17 +131,16 @@ 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)); From e785556329a764a3c8bd814a41546d3529179bed Mon Sep 17 00:00:00 2001 From: girishpanchal30 Date: Mon, 16 Nov 2026 12:04:39 +0530 Subject: [PATCH 02/13] fix: record backgrounds for every matching watcher --- .../js/modules/__tests__/background.test.js | 14 +++++ .../modules/__tests__/image-detector.test.js | 29 +++++++++ assets/js/modules/__tests__/main.test.js | 21 +++++++ assets/js/modules/background.js | 11 +++- assets/js/modules/image-detector.js | 59 +++++++++++-------- assets/js/modules/main.js | 9 ++- 6 files changed, 115 insertions(+), 28 deletions(-) diff --git a/assets/js/modules/__tests__/background.test.js b/assets/js/modules/__tests__/background.test.js index 11fb0b930..9fc18384c 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,19 @@ describe('optmlBackground', () => { }); describe('setupBackgroundImageObservation', () => { + 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 = `
diff --git a/assets/js/modules/__tests__/image-detector.test.js b/assets/js/modules/__tests__/image-detector.test.js index 91aba85d6..14303c1f2 100644 --- a/assets/js/modules/__tests__/image-detector.test.js +++ b/assets/js/modules/__tests__/image-detector.test.js @@ -211,6 +211,35 @@ 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('observeOptimoleImages', () => { diff --git a/assets/js/modules/__tests__/main.test.js b/assets/js/modules/__tests__/main.test.js index e477ab791..3f3f1ace4 100644 --- a/assets/js/modules/__tests__/main.test.js +++ b/assets/js/modules/__tests__/main.test.js @@ -314,6 +314,27 @@ describe('optmlMain', () => { 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('should send data to API when images found', async () => { // Create a real image element and add to DOM document.body.innerHTML = ''; diff --git a/assets/js/modules/background.js b/assets/js/modules/background.js index 6b956e6f6..ca4b1bea8 100644 --- a/assets/js/modules/background.js +++ b/assets/js/modules/background.js @@ -19,6 +19,13 @@ export const optmlBackground = { * @returns {number} Number of elements waiting for lazy load */ setupBackgroundImageObservation: function(elements, selector, selectorMap, observer) { + // Re-observing forces a fresh callback for elements already observed as Optimole images, + // whose first callback ran before they were marked as backgrounds. + const observeBackground = element => { + observer.unobserve(element); + observer.observe(element); + }; + // Create a single shared observer for all elements const classObserver = new MutationObserver((mutations) => { for (const mutation of mutations) { @@ -29,7 +36,7 @@ export const optmlBackground = { if (element.classList.contains('optml-bg-lazyloaded') && optmlDomUtils.hasBackgroundImage(element)) { // Start observing for visibility - observer.observe(element); + observeBackground(element); // Stop watching for class changes on this element classObserver.disconnect(element); @@ -55,7 +62,7 @@ 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); diff --git a/assets/js/modules/image-detector.js b/assets/js/modules/image-detector.js index cb81f329c..37cbefab9 100644 --- a/assets/js/modules/image-detector.js +++ b/assets/js/modules/image-detector.js @@ -82,37 +82,50 @@ export const optmlImageDetector = { 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`); - } - } + 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); + } }); }, { threshold: 0.1 // Consider element visible when 10% is in viewport }); }, + /** + * 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 1eb1f5554..c0012a445 100644 --- a/assets/js/modules/main.js +++ b/assets/js/modules/main.js @@ -13,6 +13,9 @@ 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 an element sends more URLs than this. +const MAX_BG_URLS_PER_ELEMENT = 3; + /** * Main detection functionality */ @@ -184,7 +187,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 @@ -232,8 +235,8 @@ export const optmlMain = { // 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); } }); }); From ca7ee9fc383b15e08a59ef1f466cbbad8d133cbc Mon Sep 17 00:00:00 2001 From: girishpanchal30 Date: Mon, 16 Nov 2026 12:51:33 +0530 Subject: [PATCH 03/13] fix: cap above-fold selectors per watcher --- assets/js/modules/__tests__/main.test.js | 13 +++++++++++++ assets/js/modules/main.js | 5 +++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/assets/js/modules/__tests__/main.test.js b/assets/js/modules/__tests__/main.test.js index 3f3f1ace4..129bbcbc3 100644 --- a/assets/js/modules/__tests__/main.test.js +++ b/assets/js/modules/__tests__/main.test.js @@ -335,6 +335,19 @@ describe('optmlMain', () => { 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('should send data to API when images found', async () => { // Create a real image element and add to DOM document.body.innerHTML = ''; diff --git a/assets/js/modules/main.js b/assets/js/modules/main.js index c0012a445..4f35d3936 100644 --- a/assets/js/modules/main.js +++ b/assets/js/modules/main.js @@ -13,8 +13,9 @@ 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 an element sends more URLs than this. +// 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; /** * Main detection functionality @@ -228,7 +229,7 @@ export const optmlMain = { 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; From 681af46ef8a37291043080c438d821e2e8e9f79d Mon Sep 17 00:00:00 2001 From: girishpanchal30 Date: Mon, 16 Nov 2026 14:30:43 +0530 Subject: [PATCH 04/13] fix: cap background watchers --- assets/js/modules/__tests__/main.test.js | 13 +++++++++++++ assets/js/modules/main.js | 3 ++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/assets/js/modules/__tests__/main.test.js b/assets/js/modules/__tests__/main.test.js index 129bbcbc3..811465e47 100644 --- a/assets/js/modules/__tests__/main.test.js +++ b/assets/js/modules/__tests__/main.test.js @@ -348,6 +348,19 @@ describe('optmlMain', () => { 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 = ''; diff --git a/assets/js/modules/main.js b/assets/js/modules/main.js index 4f35d3936..5c2ccf34d 100644 --- a/assets/js/modules/main.js +++ b/assets/js/modules/main.js @@ -16,6 +16,7 @@ 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 @@ -224,7 +225,7 @@ 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] = {}; From be2d28383320b917ed42a5e422733bd97d81b69d Mon Sep 17 00:00:00 2001 From: girishpanchal30 Date: Mon, 16 Nov 2026 15:48:59 +0530 Subject: [PATCH 05/13] fix: exempt every above-fold background --- .../js/modules/__tests__/background.test.js | 25 ++++++++ assets/js/modules/background.js | 57 +++++++++++-------- assets/js/modules/image-detector.js | 2 +- inc/v2/BgOptimizer/Lazyload.php | 10 +++- tests/test-bg-selector.php | 54 ++++++++++++++++++ tests/test-viewport-bg-css.php | 7 ++- 6 files changed, 126 insertions(+), 29 deletions(-) diff --git a/assets/js/modules/__tests__/background.test.js b/assets/js/modules/__tests__/background.test.js index 9fc18384c..5b8549ed8 100644 --- a/assets/js/modules/__tests__/background.test.js +++ b/assets/js/modules/__tests__/background.test.js @@ -45,6 +45,31 @@ 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'); diff --git a/assets/js/modules/background.js b/assets/js/modules/background.js index ca4b1bea8..c7470cac9 100644 --- a/assets/js/modules/background.js +++ b/assets/js/modules/background.js @@ -19,38 +19,45 @@ export const optmlBackground = { * @returns {number} Number of elements waiting for lazy load */ setupBackgroundImageObservation: function(elements, selector, selectorMap, observer) { - // Re-observing forces a fresh callback for elements already observed as Optimole images, - // whose first callback ran before they were marked as backgrounds. + /** + * 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 - observeBackground(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); @@ -65,12 +72,12 @@ export const optmlBackground = { 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'] }); }); @@ -82,7 +89,7 @@ export const optmlBackground = { }, 5000); } - return elementsToWatch.length; + return elementsToWatch.size; }, /** diff --git a/assets/js/modules/image-detector.js b/assets/js/modules/image-detector.js index 37cbefab9..77695f4b2 100644 --- a/assets/js/modules/image-detector.js +++ b/assets/js/modules/image-detector.js @@ -76,7 +76,7 @@ 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) { diff --git a/inc/v2/BgOptimizer/Lazyload.php b/inc/v2/BgOptimizer/Lazyload.php index 0c57a65e2..e89910ceb 100644 --- a/inc/v2/BgOptimizer/Lazyload.php +++ b/inc/v2/BgOptimizer/Lazyload.php @@ -143,12 +143,20 @@ private static function collect_device_selectors( array $personalized_selectors, $css_selectors[] = 'html ' . strip_tags( $selector ) . ':not(.optml-bg-lazyloaded)'; 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 watchers the profile does not list keep their generic hide rule. + foreach ( array_keys( array_diff_key( $lazyload_selectors, $personalized_selectors ) ) as $selector ) { + $css_selectors[] = 'html ' . strip_tags( $selector ) . ':not(.optml-bg-lazyloaded)'; } $css_selectors = array_unique( $css_selectors ); diff --git a/tests/test-bg-selector.php b/tests/test-bg-selector.php index f03680e2e..fdb1bfe2b 100644 --- a/tests/test-bg-selector.php +++ b/tests/test-bg-selector.php @@ -132,6 +132,60 @@ public function test_personalized_css_drops_injected_selectors(): void { $this->assertSame( '', $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 ); + } + + /** + * Issue 1216: a watcher the profile does not list, such as the 101st when the client caps + * watchers at 100, keeps its generic hide rule. + */ + public function test_personalized_css_keeps_generic_rule_for_unlisted_watchers(): void { + $watchers = array_map( + static function ( int $index ): string { + return '.bg-' . $index; + }, + range( 0, 100 ) + ); + $add_watchers = static function ( array $selectors ) use ( $watchers ): array { + return array_merge( $selectors, $watchers ); + }; + add_filter( 'optml_lazyload_bg_selectors', $add_watchers ); + $this->reset_background_selectors(); + + $bg = array_fill_keys( array_slice( $watchers, 0, 100 ), [] ); + $bg['.bg-0'] = [ '#hero' => [] ]; + $device_data = [ 'bg' => $bg ]; + + $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 ); + + $this->assertStringContainsString( 'html .bg-100:not(.optml-bg-lazyloaded)', $css ); + $this->assertStringContainsString( 'html ' . self::WATCHER . ':not(.optml-bg-lazyloaded)', $css ); + $this->assertStringContainsString( 'html .bg-0:not(#hero):not(.optml-bg-lazyloaded)', $css ); + $this->assertStringNotContainsString( 'html .bg-0:not(.optml-bg-lazyloaded)', $css ); + } + /** * An injected LCP selector voids the device rule. */ diff --git a/tests/test-viewport-bg-css.php b/tests/test-viewport-bg-css.php index ea3140999..5a378a783 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 { From 7cbde284a59926ac3397fd1e8fdb21756fb696f3 Mon Sep 17 00:00:00 2001 From: girishpanchal30 Date: Mon, 16 Nov 2026 16:00:56 +0530 Subject: [PATCH 06/13] Fix: lint tests --- assets/js/modules/__tests__/dom-utils.test.js | 73 ++++++++++++------- 1 file changed, 46 insertions(+), 27 deletions(-) diff --git a/assets/js/modules/__tests__/dom-utils.test.js b/assets/js/modules/__tests__/dom-utils.test.js index 3a7031f74..c3718a97d 100644 --- a/assets/js/modules/__tests__/dom-utils.test.js +++ b/assets/js/modules/__tests__/dom-utils.test.js @@ -293,12 +293,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 +332,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(); }); }); }); From b404f54339904d60ed7fa8a6705e74a232a62326 Mon Sep 17 00:00:00 2001 From: girishpanchal30 Date: Tue, 17 Nov 2026 12:36:31 +0530 Subject: [PATCH 07/13] fix: optimize class name processing --- assets/js/modules/__tests__/dom-utils.test.js | 14 ++++++++++++++ assets/js/modules/dom-utils.js | 15 +++++---------- inc/v2/BgOptimizer/Lazyload.php | 4 ---- 3 files changed, 19 insertions(+), 14 deletions(-) diff --git a/assets/js/modules/__tests__/dom-utils.test.js b/assets/js/modules/__tests__/dom-utils.test.js index c3718a97d..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'); 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/inc/v2/BgOptimizer/Lazyload.php b/inc/v2/BgOptimizer/Lazyload.php index e89910ceb..20be58a0c 100644 --- a/inc/v2/BgOptimizer/Lazyload.php +++ b/inc/v2/BgOptimizer/Lazyload.php @@ -139,10 +139,6 @@ 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)'; - 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 ) { From 3fc86e30a85224b1289067fbbe12ff893fe66404 Mon Sep 17 00:00:00 2001 From: girishpanchal30 Date: Tue, 17 Nov 2026 13:12:19 +0530 Subject: [PATCH 08/13] fix: use Lazyload constants for background selector limits --- inc/rest.php | 5 ++- inc/v2/BgOptimizer/Lazyload.php | 22 ++++++++-- tests/test-bg-selector.php | 75 +++++++++++++++++++++++++++------ 3 files changed, 84 insertions(+), 18 deletions(-) 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 20be58a0c..bfe77cc67 100644 --- a/inc/v2/BgOptimizer/Lazyload.php +++ b/inc/v2/BgOptimizer/Lazyload.php @@ -18,6 +18,16 @@ 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; + /** * Check whether a client-reported selector is a plain selector safe to embed in the stylesheet as-is. * @@ -139,6 +149,10 @@ private static function collect_device_selectors( array $personalized_selectors, if ( ! isset( $lazyload_selectors[ $selector ] ) ) { continue; } + // 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 ) { @@ -150,9 +164,11 @@ private static function collect_device_selectors( array $personalized_selectors, $css_selectors[] = 'html ' . strip_tags( $selector ) . $exemptions . ':not(.optml-bg-lazyloaded)'; } - // This CSS replaces the generic one, so watchers the profile does not list keep their generic hide rule. - foreach ( array_keys( array_diff_key( $lazyload_selectors, $personalized_selectors ) ) as $selector ) { - $css_selectors[] = 'html ' . strip_tags( $selector ) . ':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)'; + } } $css_selectors = array_unique( $css_selectors ); diff --git a/tests/test-bg-selector.php b/tests/test-bg-selector.php index fdb1bfe2b..9f2136ae0 100644 --- a/tests/test-bg-selector.php +++ b/tests/test-bg-selector.php @@ -152,26 +152,78 @@ public function test_personalized_css_exempts_all_above_fold_elements_in_one_rul } /** - * Issue 1216: a watcher the profile does not list, such as the 101st when the client caps - * watchers at 100, keeps its generic hide rule. + * 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, 100 ) + range( 0, Lazyload::MAX_WATCHERS ) ); - $add_watchers = static function ( array $selectors ) use ( $watchers ): array { - return array_merge( $selectors, $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 ); + } + + /** + * 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(); - $bg = array_fill_keys( array_slice( $watchers, 0, 100 ), [] ); - $bg['.bg-0'] = [ '#hero' => [] ]; - $device_data = [ 'bg' => $bg ]; - $css = Lazyload::get_personalized_css( [ Profile::DEVICE_TYPE_MOBILE => $device_data, @@ -180,10 +232,7 @@ static function ( int $index ): string { ); remove_filter( 'optml_lazyload_bg_selectors', $add_watchers ); - $this->assertStringContainsString( 'html .bg-100:not(.optml-bg-lazyloaded)', $css ); - $this->assertStringContainsString( 'html ' . self::WATCHER . ':not(.optml-bg-lazyloaded)', $css ); - $this->assertStringContainsString( 'html .bg-0:not(#hero):not(.optml-bg-lazyloaded)', $css ); - $this->assertStringNotContainsString( 'html .bg-0:not(.optml-bg-lazyloaded)', $css ); + return $css; } /** From 31b90379a39bf5785e7dc480708c8d7bb5c86474 Mon Sep 17 00:00:00 2001 From: girishpanchal30 Date: Tue, 17 Nov 2026 17:03:40 +0530 Subject: [PATCH 09/13] fix: improve personalized CSS handling --- inc/manager.php | 2 +- inc/v2/BgOptimizer/Lazyload.php | 49 ++++++++++++++++----------------- tests/test-bg-selector.php | 37 ++++++++++++++++++++----- tests/test-viewport-bg-css.php | 32 +++++++++++++++++++++ 4 files changed, 86 insertions(+), 34 deletions(-) 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/v2/BgOptimizer/Lazyload.php b/inc/v2/BgOptimizer/Lazyload.php index bfe77cc67..c4b72ea8d 100644 --- a/inc/v2/BgOptimizer/Lazyload.php +++ b/inc/v2/BgOptimizer/Lazyload.php @@ -28,6 +28,11 @@ class Lazyload { */ const MAX_ABOVE_FOLD_SELECTORS = 100; + /** + * Viewport width in px that splits the mobile and desktop rules. + */ + private const DEVICE_BREAKPOINT = 600; + /** * Check whether a client-reported selector is a plain selector safe to embed in the stylesheet as-is. * @@ -56,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() ); } /** @@ -66,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 = []; @@ -104,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 . '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. diff --git a/tests/test-bg-selector.php b/tests/test-bg-selector.php index 9f2136ae0..1bf130438 100644 --- a/tests/test-bg-selector.php +++ b/tests/test-bg-selector.php @@ -127,9 +127,7 @@ 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 ); } /** @@ -206,6 +204,33 @@ public function test_personalized_css_skips_watcher_with_full_above_fold_list(): $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: 600px) { html .bg-0:not(#hero-1)', $css ); + $this->assertStringNotContainsString( 'max-width', $css ); + } + /** * Build the personalized CSS for both devices with extra watchers .bg-0 … .bg-{count-1} registered. * @@ -254,8 +279,7 @@ public function test_personalized_css_drops_injected_lcp_selector(): void { ] ); - $this->assertStringNotContainsString( 'background:red', $css ); - $this->assertSame( '', $css ); + $this->assertNull( $css ); } /** @@ -278,8 +302,7 @@ public function test_personalized_css_drops_rule_when_any_selector_unsafe(): voi ] ); - $this->assertStringNotContainsString( 'background:red', $css ); - $this->assertSame( '', $css ); + $this->assertNull( $css ); } /** diff --git a/tests/test-viewport-bg-css.php b/tests/test-viewport-bg-css.php index 5a378a783..3932f20c3 100644 --- a/tests/test-viewport-bg-css.php +++ b/tests/test-viewport-bg-css.php @@ -214,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 ); + } } From 0ece477b7892c65dc4366a3c5a9558e35de42965 Mon Sep 17 00:00:00 2001 From: girishpanchal30 Date: Wed, 18 Nov 2026 10:57:57 +0530 Subject: [PATCH 10/13] fix: enhance image detection and intersection observer handling --- .../modules/__tests__/image-detector.test.js | 15 +++++ assets/js/modules/__tests__/main.test.js | 17 +++++ assets/js/modules/image-detector.js | 63 +++++++++++++------ assets/js/modules/main.js | 3 + inc/v2/BgOptimizer/Lazyload.php | 4 +- tests/test-bg-selector.php | 20 +++++- 6 files changed, 100 insertions(+), 22 deletions(-) diff --git a/assets/js/modules/__tests__/image-detector.test.js b/assets/js/modules/__tests__/image-detector.test.js index 14303c1f2..ce5ba6abc 100644 --- a/assets/js/modules/__tests__/image-detector.test.js +++ b/assets/js/modules/__tests__/image-detector.test.js @@ -242,6 +242,21 @@ describe('optmlImageDetector', () => { }); }); + 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']); + }); + }); + describe('observeOptimoleImages', () => { test('should observe all images with data-opt-id', () => { document.body.innerHTML = ` diff --git a/assets/js/modules/__tests__/main.test.js b/assets/js/modules/__tests__/main.test.js index 811465e47..0f5059195 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() @@ -410,6 +411,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(); diff --git a/assets/js/modules/image-detector.js b/assets/js/modules/image-detector.js index 77695f4b2..675180e85 100644 --- a/assets/js/modules/image-detector.js +++ b/assets/js/modules/image-detector.js @@ -81,30 +81,57 @@ export const optmlImageDetector = { */ createIntersectionObserver: function(aboveTheFoldImages, selectorMap) { return new IntersectionObserver(entries => { - entries.forEach(entry => { - if (!entry.isIntersecting) { - return; - } - const element = entry.target; + this.recordIntersections(entries, aboveTheFoldImages, selectorMap); + }, { + threshold: 0.1 // Consider element visible when 10% is in viewport + }); + }, - // 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); - } - } + /** + * 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; - // An img can also carry a background image, so this is checked independently. - if (element.hasAttribute('data-optml-bg-selector')) { - this.recordAboveFoldBackground(element, selectorMap); + // 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); } - }); - }, { - threshold: 0.1 // Consider element visible when 10% is in viewport + } + + // 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 diff --git a/assets/js/modules/main.js b/assets/js/modules/main.js index 5c2ccf34d..67d386864 100644 --- a/assets/js/modules/main.js +++ b/assets/js/modules/main.js @@ -151,6 +151,9 @@ export const optmlMain = { 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); + // Disconnect observer and clean up event listeners observer.disconnect(); window.removeEventListener('resize', resizeHandler); diff --git a/inc/v2/BgOptimizer/Lazyload.php b/inc/v2/BgOptimizer/Lazyload.php index c4b72ea8d..15f8081f1 100644 --- a/inc/v2/BgOptimizer/Lazyload.php +++ b/inc/v2/BgOptimizer/Lazyload.php @@ -29,7 +29,7 @@ class Lazyload { const MAX_ABOVE_FOLD_SELECTORS = 100; /** - * Viewport width in px that splits the mobile and desktop rules. + * Widest viewport in px the profiler counts as mobile (MOBILE_BREAKPOINT in device.js). */ private const DEVICE_BREAKPOINT = 600; @@ -127,7 +127,7 @@ public static function get_personalized_css( $data ): ?string { $media_queries[] = '@media (max-width: ' . self::DEVICE_BREAKPOINT . 'px) { ' . $mobile_selectors . $hide_rule . ' }'; } if ( $desktop_selectors !== '' ) { - $media_queries[] = '@media (min-width: ' . self::DEVICE_BREAKPOINT . 'px) { ' . $desktop_selectors . $hide_rule . ' }'; + $media_queries[] = '@media (min-width: ' . ( self::DEVICE_BREAKPOINT + 1 ) . 'px) { ' . $desktop_selectors . $hide_rule . ' }'; } return implode( ' ', $media_queries ); } diff --git a/tests/test-bg-selector.php b/tests/test-bg-selector.php index 1bf130438..f1cb2a3bc 100644 --- a/tests/test-bg-selector.php +++ b/tests/test-bg-selector.php @@ -227,10 +227,26 @@ public function test_personalized_css_scopes_other_device_rule_when_one_device_i remove_filter( 'optml_lazyload_bg_selectors', $only_watcher ); $this->assertIsString( $css ); - $this->assertStringStartsWith( '@media (min-width: 600px) { html .bg-0:not(#hero-1)', $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. * @@ -326,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 ); From 03ee02f3041e94247ca32b3e1fcbef5e06a68b85 Mon Sep 17 00:00:00 2001 From: girishpanchal30 Date: Wed, 18 Nov 2026 11:10:26 +0530 Subject: [PATCH 11/13] chore: update E2E tests to run on Ubuntu 24.04 --- .github/workflows/test-e2e.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From d3478412b01f2c55da1c3c69b6f9215381091555 Mon Sep 17 00:00:00 2001 From: girishpanchal30 Date: Wed, 18 Nov 2026 12:09:50 +0530 Subject: [PATCH 12/13] fix: add test for recording queued entries in hidden tabs --- .../modules/__tests__/image-detector.test.js | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/assets/js/modules/__tests__/image-detector.test.js b/assets/js/modules/__tests__/image-detector.test.js index ce5ba6abc..9c2841362 100644 --- a/assets/js/modules/__tests__/image-detector.test.js +++ b/assets/js/modules/__tests__/image-detector.test.js @@ -255,6 +255,29 @@ describe('optmlImageDetector', () => { 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', () => { From 1ad036a35a629956177524b620e9c8a43fb20d3c Mon Sep 17 00:00:00 2001 From: girishpanchal30 Date: Wed, 18 Nov 2026 12:12:13 +0530 Subject: [PATCH 13/13] fix: update image dimension detection to handle late-loading images --- assets/js/modules/__tests__/main.test.js | 24 ++++++++++++++++++++++++ assets/js/modules/main.js | 10 +++++----- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/assets/js/modules/__tests__/main.test.js b/assets/js/modules/__tests__/main.test.js index 0f5059195..f71b76514 100644 --- a/assets/js/modules/__tests__/main.test.js +++ b/assets/js/modules/__tests__/main.test.js @@ -266,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(); diff --git a/assets/js/modules/main.js b/assets/js/modules/main.js index 67d386864..48acc6513 100644 --- a/assets/js/modules/main.js +++ b/assets/js/modules/main.js @@ -118,11 +118,6 @@ export const optmlMain = { // 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; @@ -154,6 +149,11 @@ export const optmlMain = { // 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);