From 56209c98a4c05b6e27f13b5b37c7b739d0563692 Mon Sep 17 00:00:00 2001
From: girishpanchal30
Date: Mon, 16 Nov 2026 11:12:23 +0530
Subject: [PATCH 01/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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/19] 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 9ea26d1b775ce567f89a5e6810d656e29f70f4f1 Mon Sep 17 00:00:00 2001
From: Girish Panchal <79647963+girishpanchal30@users.noreply.github.com>
Date: Tue, 17 Nov 2026 14:32:02 +0530
Subject: [PATCH 09/19] Fixed attach cloud library listeners early (#1241)
* fix: attach cloud library listeners early
* ci: build assets before PHPUnit tests
* fix: phpunit tests
* Revert "ci: build assets before PHPUnit tests"
This reverts commit 8f8b34c222dee5e05c8fbdff09bc25f241115a17.
---
assets/src/media/__tests__/admin-page.test.js | 38 +++++++++++++++++++
assets/src/media/admin-page.js | 14 ++++---
inc/dam.php | 4 +-
tests/test-dam.php | 13 +++++++
4 files changed, 62 insertions(+), 7 deletions(-)
create mode 100644 assets/src/media/__tests__/admin-page.test.js
diff --git a/assets/src/media/__tests__/admin-page.test.js b/assets/src/media/__tests__/admin-page.test.js
new file mode 100644
index 000000000..fa041c329
--- /dev/null
+++ b/assets/src/media/__tests__/admin-page.test.js
@@ -0,0 +1,38 @@
+/**
+ * Tests for the Cloud Library admin page script.
+ */
+
+jest.mock( '../scss/admin-page.scss', () => ({}) );
+
+const SITE_URL = 'https://example.test';
+
+describe( 'Cloud Library admin page (issue #1211)', () => {
+ let iframe;
+ let loader;
+
+ beforeAll( () => {
+ window.optmlAdminPage = { siteUrl: SITE_URL };
+
+ // The script is printed in the head, before the iframe markup exists.
+ require( '../admin-page.js' );
+
+ document.body.innerHTML = '';
+ iframe = document.getElementById( 'om-dam' );
+ loader = document.querySelector( '.om-dam-loader' );
+ });
+
+ test( 'reveals the iframe when it loads after the script ran', () => {
+ iframe.dispatchEvent( new Event( 'load' ) );
+
+ expect( loader.style.display ).toBe( 'none' );
+ expect( iframe.style.display ).toBe( '' );
+ });
+
+ test( 'answers getUrl from an iframe added after the script ran', () => {
+ const postMessage = jest.spyOn( iframe.contentWindow, 'postMessage' ).mockImplementation( () => {});
+
+ window.dispatchEvent( new MessageEvent( 'message', { data: { type: 'om-dam', action: 'getUrl' }}) );
+
+ expect( postMessage ).toHaveBeenCalledWith({ siteUrl: SITE_URL, type: 'om-dam', context: 'browse' }, '*' );
+ });
+});
diff --git a/assets/src/media/admin-page.js b/assets/src/media/admin-page.js
index f861a2fa1..2d7a6692b 100644
--- a/assets/src/media/admin-page.js
+++ b/assets/src/media/admin-page.js
@@ -3,12 +3,16 @@ import './scss/admin-page.scss';
const { optmlAdminPage } = window;
const { siteUrl } = optmlAdminPage;
-const iframe = document.getElementById( 'om-dam' );
-iframe.addEventListener( 'load', function() {
+// This runs in the head, before #om-dam exists: `load` does not bubble, so catch it in the capture phase.
+document.addEventListener( 'load', function( event ) {
+ if ( 'om-dam' !== event.target.id ) {
+ return;
+ }
+
document.querySelector( '.om-dam-loader' ).style.display = 'none';
- iframe.style.display = '';
-});
+ event.target.style.display = '';
+}, true );
window.addEventListener( 'message', function( event ) {
if ( ! event.data ) {
@@ -31,5 +35,5 @@ window.addEventListener( 'message', function( event ) {
return;
}
- iframe.contentWindow.postMessage({ siteUrl, type: 'om-dam', context: 'browse' }, '*' );
+ document.getElementById( 'om-dam' ).contentWindow.postMessage({ siteUrl, type: 'om-dam', context: 'browse' }, '*' );
});
diff --git a/inc/dam.php b/inc/dam.php
index 8bbeb4c99..5744e5a39 100644
--- a/inc/dam.php
+++ b/inc/dam.php
@@ -429,12 +429,12 @@ public function render_dashboard_page() {
display: none !important;
}
-
...
+
assertEmpty( $data['sites'] );
}
+ public function test_dashboard_page_renders_loader_before_iframe_issue_1211() {
+ ob_start();
+ $this->dam->render_dashboard_page();
+ $html = ob_get_clean();
+
+ $loader = strpos( $html, 'class="om-dam-loader"' );
+ $iframe = strpos( $html, 'id="om-dam"' );
+
+ $this->assertNotFalse( $loader );
+ $this->assertNotFalse( $iframe );
+ $this->assertLessThan( $iframe, $loader );
+ }
+
public function test_insert_attachments() {
foreach ( $this->inserted_ids as $index => $id ) {
$this->assertIsInt( $id );
From 31b90379a39bf5785e7dc480708c8d7bb5c86474 Mon Sep 17 00:00:00 2001
From: girishpanchal30
Date: Tue, 17 Nov 2026 17:03:40 +0530
Subject: [PATCH 10/19] 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 11/19] 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 12/19] 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 13/19] 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 14/19] 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);
From 80865437d14dcb2dd8ac7fbd0436fa04b6652883 Mon Sep 17 00:00:00 2001
From: selul
Date: Wed, 18 Nov 2026 11:34:04 +0200
Subject: [PATCH 15/19] chore(deps-dev): bump @playwright/test to 1.61.1 for
the Ubuntu 26.04 runner
The e2e job runs on ubuntu-latest, which now resolves to Ubuntu 26.04.
Playwright 1.50.1 has no browser builds for it, so the job stopped at
"npx playwright install" with "Playwright does not support chromium on
ubuntu26.04-x64". 1.61.0 is the first release that supports the image.
Co-Authored-By: Claude Fable 5.2
---
package-lock.json | 46 +++++++++++++++++++++++-----------------------
package.json | 2 +-
2 files changed, 24 insertions(+), 24 deletions(-)
diff --git a/package-lock.json b/package-lock.json
index 0c0a8ae61..62826add8 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -14,7 +14,7 @@
"usehooks-ts": "^2.9.1"
},
"devDependencies": {
- "@playwright/test": "^1.50.1",
+ "@playwright/test": "^1.61.1",
"@semantic-release/changelog": "^5.0.1",
"@semantic-release/exec": "^5.0.0",
"@semantic-release/git": "^9.0.0",
@@ -3285,13 +3285,13 @@
}
},
"node_modules/@playwright/test": {
- "version": "1.50.1",
- "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.50.1.tgz",
- "integrity": "sha512-Jii3aBg+CEDpgnuDxEp/h7BimHcUTDlpEtce89xEumlJ5ef2hqepZ+PWp1DDpYC/VO9fmWVI1IlEaoI5fK9FXQ==",
+ "version": "1.61.1",
+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.61.1.tgz",
+ "integrity": "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
- "playwright": "1.50.1"
+ "playwright": "1.61.1"
},
"bin": {
"playwright": "cli.js"
@@ -22408,13 +22408,13 @@
}
},
"node_modules/playwright": {
- "version": "1.50.1",
- "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.50.1.tgz",
- "integrity": "sha512-G8rwsOQJ63XG6BbKj2w5rHeavFjy5zynBA9zsJMMtBoe/Uf757oG12NXz6e6OirF7RCrTVAKFXbLmn1RbL7Qaw==",
+ "version": "1.61.1",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz",
+ "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
- "playwright-core": "1.50.1"
+ "playwright-core": "1.61.1"
},
"bin": {
"playwright": "cli.js"
@@ -22439,9 +22439,9 @@
}
},
"node_modules/playwright/node_modules/playwright-core": {
- "version": "1.50.1",
- "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.50.1.tgz",
- "integrity": "sha512-ra9fsNWayuYumt+NiM069M6OkcRb1FZSK8bgi66AtpFoWkg2+y0bJSNmkFrWhMbEBbVKC/EruAHH3g0zmtwGmQ==",
+ "version": "1.61.1",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz",
+ "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==",
"dev": true,
"license": "Apache-2.0",
"bin": {
@@ -32765,12 +32765,12 @@
"dev": true
},
"@playwright/test": {
- "version": "1.50.1",
- "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.50.1.tgz",
- "integrity": "sha512-Jii3aBg+CEDpgnuDxEp/h7BimHcUTDlpEtce89xEumlJ5ef2hqepZ+PWp1DDpYC/VO9fmWVI1IlEaoI5fK9FXQ==",
+ "version": "1.61.1",
+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.61.1.tgz",
+ "integrity": "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==",
"dev": true,
"requires": {
- "playwright": "1.50.1"
+ "playwright": "1.61.1"
}
},
"@pmmmwh/react-refresh-webpack-plugin": {
@@ -47090,19 +47090,19 @@
}
},
"playwright": {
- "version": "1.50.1",
- "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.50.1.tgz",
- "integrity": "sha512-G8rwsOQJ63XG6BbKj2w5rHeavFjy5zynBA9zsJMMtBoe/Uf757oG12NXz6e6OirF7RCrTVAKFXbLmn1RbL7Qaw==",
+ "version": "1.61.1",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz",
+ "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==",
"dev": true,
"requires": {
"fsevents": "2.3.2",
- "playwright-core": "1.50.1"
+ "playwright-core": "1.61.1"
},
"dependencies": {
"playwright-core": {
- "version": "1.50.1",
- "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.50.1.tgz",
- "integrity": "sha512-ra9fsNWayuYumt+NiM069M6OkcRb1FZSK8bgi66AtpFoWkg2+y0bJSNmkFrWhMbEBbVKC/EruAHH3g0zmtwGmQ==",
+ "version": "1.61.1",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz",
+ "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==",
"dev": true
}
}
diff --git a/package.json b/package.json
index 7ae2996a0..f4ac7b606 100755
--- a/package.json
+++ b/package.json
@@ -49,7 +49,7 @@
"make-pot": "docker run --user root --rm --volume $(pwd):/var/www/html/optimole-wp wordpress:cli bash -c 'php -d memory_limit=512M $(which wp) --version --allow-root && wp i18n make-pot optimole-wp ./optimole-wp/languages/optimole-wp.pot --include=inc,assets/src --allow-root --domain=optimole-wp'"
},
"devDependencies": {
- "@playwright/test": "^1.50.1",
+ "@playwright/test": "^1.61.1",
"@semantic-release/changelog": "^5.0.1",
"@semantic-release/exec": "^5.0.0",
"@semantic-release/git": "^9.0.0",
From d1a7f819828892feb48d8d9b5b20df5b8c181964 Mon Sep 17 00:00:00 2001
From: Marius Cristea
Date: Wed, 18 Nov 2026 11:39:55 +0200
Subject: [PATCH 16/19] fix: stop adding the language code twice to upgrade
links (#1243)
Three upgrade links (the Media Library upgrade notice, the Black Friday
sidebar offer and the disabled-account notice) localized the result of
get_upgrade_base_link() a second time and pointed to /de/de/upgrade,
which is a 404 on optimole.com. The link is now localized once.
Co-Authored-By: Claude Fable 5.2
---
inc/admin.php | 8 +-
tests/test-upgrade-link.php | 229 ++++++++++++++++++++++++++++++++++++
2 files changed, 234 insertions(+), 3 deletions(-)
create mode 100644 tests/test-upgrade-link.php
diff --git a/inc/admin.php b/inc/admin.php
index 0641d2599..4438d099a 100755
--- a/inc/admin.php
+++ b/inc/admin.php
@@ -717,7 +717,7 @@ public function add_notice_upgrade() {
?>
-
@@ -772,6 +772,8 @@ public function should_show_upgrade() {
/**
* Build upgrade URL with current user's encoded email.
*
+ * The URL is already localized, so callers must not pass it through tsdk_translate_link() again.
+ *
* @return string Upgrade URL.
*/
public static function get_upgrade_base_link() {
@@ -1741,7 +1743,7 @@ public function get_bf_notices( $user_plan ) {
'' . $promo_code . '',
'' . __( '25% discount', 'optimole-wp' ) . ''
),
- 'cta_link' => esc_url_raw( tsdk_utmify( tsdk_translate_link( self::get_upgrade_base_link() ), 'bfcm', 'sidebarnotice' ) ),
+ 'cta_link' => esc_url_raw( tsdk_utmify( self::get_upgrade_base_link(), 'bfcm', 'sidebarnotice' ) ),
];
// The banner shares the SDK dismissal, which resets every year.
@@ -1914,7 +1916,7 @@ private function get_dashboard_strings() {
'notice_disabled_account' => sprintf(
/* translators: 1 anchor tag to pricing, 2 is the ending endin anchor tag, 3 is the bold tag start, 4 ending bold tag, 5 new line tag */
__( '%3$sYour account has been disabled due to exceeding quota.%4$s All images are being redirected to the original unoptimized URL. %5$sPlease %1$supgrade%2$s to re-activate the account.', 'optimole-wp' ),
- '',
+ '',
'',
'',
'',
diff --git a/tests/test-upgrade-link.php b/tests/test-upgrade-link.php
new file mode 100644
index 000000000..f713f59ae
--- /dev/null
+++ b/tests/test-upgrade-link.php
@@ -0,0 +1,229 @@
+initial_service_data = $settings->get( 'service_data' );
+
+ $settings->update(
+ 'service_data',
+ [
+ 'cdn_key' => 'example',
+ 'cdn_secret' => 'test',
+ 'whitelist' => [ 'example.org' ],
+ 'user_email' => self::ACCOUNT_EMAIL,
+ 'plan' => 'free',
+ 'visitors_limit' => 2000,
+ 'visitors_left' => 100,
+ ]
+ );
+ }
+
+ /**
+ * Restore the settings, which outlive the database rollback because they are cached statically.
+ */
+ public function tearDown(): void {
+ ( new Optml_Settings() )->update( 'service_data', $this->initial_service_data );
+
+ remove_all_filters( 'themeisle_sdk_is_black_friday_sale' );
+ remove_all_filters( 'themeisle_sdk_current_date' );
+ set_current_screen( 'front' );
+
+ parent::tearDown();
+ }
+
+ /**
+ * Locales for which the SDK adds a language code to a link, with that code.
+ *
+ * @return array
+ */
+ public function localized_locales(): array {
+ return [
+ 'de_DE' => [ 'de_DE', 'de' ],
+ 'de_DE_formal' => [ 'de_DE_formal', 'de' ],
+ 'es_ES' => [ 'es_ES', 'es' ],
+ 'fr_FR' => [ 'fr_FR', 'fr' ],
+ 'it_IT' => [ 'it_IT', 'it' ],
+ 'ja' => [ 'ja', 'ja' ],
+ 'nl_NL' => [ 'nl_NL', 'nl' ],
+ 'nl_NL_formal' => [ 'nl_NL_formal', 'nl' ],
+ 'ro_RO' => [ 'ro_RO', 'ro' ],
+ ];
+ }
+
+ /**
+ * Log in an administrator who uses the given locale, and check how the SDK localizes links for them.
+ *
+ * @param string $locale User locale.
+ * @param string $code Language code the SDK uses for that locale, empty when it uses none.
+ */
+ private function login_admin_with_locale( string $locale = 'de_DE', string $code = 'de' ): void {
+ wp_set_current_user(
+ self::factory()->user->create(
+ [
+ 'role' => 'administrator',
+ 'locale' => $locale,
+ ]
+ )
+ );
+
+ $this->assertSame( $locale, get_user_locale() );
+ $this->assertSame(
+ '' === $code ? 'https://example.org/page/' : "https://example.org/$code/page/",
+ tsdk_translate_link( 'https://example.org/page/' )
+ );
+ }
+
+ /**
+ * Assert a link is the upgrade page with the language code once, carrying the encoded account email.
+ *
+ * @param string $link Link to check.
+ * @param string $code Expected language code, empty for none.
+ * @param string $message Failure message.
+ */
+ private function assert_upgrade_link( string $link, string $code = 'de', string $message = '' ): void {
+ $path = '' === $code ? '/upgrade' : "/$code/upgrade";
+
+ $this->assertStringStartsWith( "https://optimole.com$path?email=", $link, $message );
+
+ parse_str( (string) wp_parse_url( $link, PHP_URL_QUERY ), $query );
+ $this->assertSame( self::ACCOUNT_EMAIL, base64_decode( $query['email'] ), $message );
+ }
+
+ /**
+ * Get the optimole.com links of some markup.
+ *
+ * @param string $html Markup.
+ *
+ * @return string[]
+ */
+ private function get_optimole_links( string $html ): array {
+ preg_match_all( '~href="(https://optimole\.com/[^"]*)"~', $html, $matches );
+
+ return array_map( 'html_entity_decode', $matches[1] );
+ }
+
+ /**
+ * The upgrade link has the language code of the user once, and keeps the account email.
+ *
+ * @dataProvider localized_locales
+ *
+ * @param string $locale User locale.
+ * @param string $code Language code the SDK uses for that locale.
+ */
+ public function test_upgrade_link_has_the_language_code_once( string $locale, string $code ): void {
+ $this->login_admin_with_locale( $locale, $code );
+
+ $this->assert_upgrade_link( Optml_Admin::get_upgrade_base_link(), $code );
+ }
+
+ /**
+ * A locale the SDK does not localize gets the upgrade link without a language code.
+ */
+ public function test_upgrade_link_has_no_language_code_for_other_locales(): void {
+ $this->login_admin_with_locale( 'en_US', '' );
+
+ $this->assert_upgrade_link( Optml_Admin::get_upgrade_base_link(), '' );
+ }
+
+ /**
+ * The Media Library upgrade notice does not add the language code a second time.
+ */
+ public function test_upgrade_notice_link_has_the_language_code_once(): void {
+ $this->login_admin_with_locale();
+ set_current_screen( 'upload' );
+
+ ob_start();
+ ( new Optml_Admin() )->add_notice_upgrade();
+ $output = (string) ob_get_clean();
+
+ $links = $this->get_optimole_links( $output );
+
+ $this->assertCount( 1, $links );
+ $this->assert_upgrade_link( $links[0] );
+ }
+
+ /**
+ * Neither Black Friday notice adds the language code a second time.
+ */
+ public function test_black_friday_links_have_the_language_code_once(): void {
+ $this->login_admin_with_locale();
+ add_filter( 'themeisle_sdk_is_black_friday_sale', '__return_true' );
+ add_filter(
+ 'themeisle_sdk_current_date',
+ static function () {
+ return new DateTime( 'last Friday of November ' . gmdate( 'Y' ) );
+ }
+ );
+
+ $notices = ( new Optml_Admin() )->get_bf_notices( 'free' );
+
+ foreach ( [ 'sidebar', 'banner' ] as $notice ) {
+ $this->assertArrayHasKey( $notice, $notices );
+ $this->assert_upgrade_link( $notices[ $notice ]['cta_link'], 'de', "Wrong upgrade link in the $notice notice." );
+ }
+ }
+
+ /**
+ * Nothing the dashboard app receives links to optimole.com with two language codes.
+ */
+ public function test_dashboard_data_has_no_doubled_language_code(): void {
+ $this->login_admin_with_locale();
+
+ $localize = new ReflectionMethod( Optml_Admin::class, 'localize_dashboard_app' );
+ $localize->setAccessible( true );
+ $data = $localize->invoke( new Optml_Admin() );
+
+ $this->assert_upgrade_link( $data['upgrade_url'] );
+
+ $disabled_account_links = $this->get_optimole_links( $data['strings']['notice_disabled_account'] );
+ $this->assertCount( 1, $disabled_account_links );
+ $this->assert_upgrade_link( $disabled_account_links[0] );
+
+ array_walk_recursive(
+ $data,
+ function ( $value, $key ) {
+ if ( is_string( $value ) ) {
+ $this->assertDoesNotMatchRegularExpression( self::DOUBLED_LANGUAGE_PATTERN, $value, "Doubled language code in '$key'." );
+ }
+ }
+ );
+ }
+}
From a6b31440a159555d615ca2497f75a90d91fbbc23 Mon Sep 17 00:00:00 2001
From: Girish Panchal <79647963+girishpanchal30@users.noreply.github.com>
Date: Thu, 19 Nov 2026 19:31:50 +0530
Subject: [PATCH 17/19] Improve lazy loading for iframe and video content
replacement (#1244)
* fix: improve iframe and video lazyload content replacement
* fix: enhance lazyload handling for video and iframe elements
* docs: narrow JSON-escaped markup note to iframes
---
inc/lazyload_replacer.php | 76 ++++++++++++++++++++++++++++++---------
tests/test-lazyload.php | 52 +++++++++++++++++++++++++++
2 files changed, 111 insertions(+), 17 deletions(-)
diff --git a/inc/lazyload_replacer.php b/inc/lazyload_replacer.php
index de740ce49..86db4b793 100644
--- a/inc/lazyload_replacer.php
+++ b/inc/lazyload_replacer.php
@@ -30,6 +30,17 @@ final class Optml_Lazyload_Replacer extends Optml_App_Replacer {
const IFRAME_PLACEHOLDER_STYLE = '';
const SVG_PLACEHOLDER = 'data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%20#width#%20#height#%22%20width%3D%22#width#%22%20height%3D%22#height#%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Crect%20width%3D%22#width#%22%20height%3D%22#height#%22%20fill%3D%22#fill#%22%2F%3E%3C%2Fsvg%3E';
+ /**
+ * What precedes a start tag attribute: whitespace or, as browsers allow, directly a quoted value.
+ */
+ private const TAG_ATTRIBUTE_SEPARATOR = '(?:\s+|(?<=["\']))';
+ /**
+ * One start tag attribute with its separator.
+ *
+ * A quoted value is matched whole, so text inside it is never read as an attribute. An iframe whose
+ * attribute value starts with a backslash is not matched, so JSON-escaped iframe markup is left as written.
+ */
+ private const TAG_ATTRIBUTE = self::TAG_ATTRIBUTE_SEPARATOR . '[^\s"\'>\/=]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|[^\s"\'>\\\\][^\s>]*))?';
/**
* If frame lazyload is present on page.
*
@@ -374,14 +385,16 @@ public function lazyload_video_replace( $content ) {
$video_tags = [];
$iframes = [];
$videos = [];
- preg_match_all( '#(?:)?#is', $content, $iframes );
+ // Only iframes with no fallback content; one with fallback text is left as written.
+ preg_match_all( '#(?:)?#i', $content, $iframes );
preg_match_all( '#(?:)?#is', $content, $videos );
+ $iframe_count = count( $iframes[0] );
$video_tags = array_merge( $iframes[0], $videos[0] );
$search = [];
$replace = [];
- foreach ( $video_tags as $video_tag ) {
+ foreach ( $video_tags as $index => $video_tag ) {
if ( ! $this->should_lazyload_iframe( $video_tag ) ) {
continue;
@@ -389,23 +402,12 @@ public function lazyload_video_replace( $content ) {
if ( preg_match( "/ data-opt-src=['\"]/is", $video_tag ) ) {
continue;
}
- $should_add_noscript = true;
$original_tag = $video_tag;
- // replace the src and add the data-opt-src attribute
- if ( strpos( $video_tag, 'iframe' ) !== false ) {
- $video_tag = preg_replace( '/iframe(.*?)src=/is', 'iframe$1 src="about:blank" data-opt-src=', $video_tag );
- } elseif ( strpos( $video_tag, 'video' ) !== false ) {
- if ( strpos( $video_tag, 'source' ) !== false ) {
- if ( strpos( $video_tag, 'preload' ) === false ) {
- $video_tag = preg_replace( '/video(.*?)>/is', 'video$1 preload="metadata">', $video_tag, 1 );
- $should_add_noscript = false;
- } else {
- continue;
- }
- } else {
- $video_tag = preg_replace( '/video(.*?)src=/is', 'video$1 data-opt-src=', $video_tag );
- }
+ $lazyloaded = $this->lazyload_media_element( $video_tag, $index < $iframe_count );
+ if ( null === $lazyloaded ) {
+ continue;
}
+ list( $video_tag, $should_add_noscript ) = $lazyloaded;
if ( $this->should_add_noscript( $video_tag ) && $should_add_noscript ) {
$video_tag .= '';
}
@@ -419,6 +421,46 @@ public function lazyload_video_replace( $content ) {
return $content;
}
+ /**
+ * Move the src of a matched iframe or video to data-opt-src, or ask a sourced video to preload metadata only.
+ *
+ * @param string $element The iframe or video element.
+ * @param bool $is_iframe Whether the element was matched as an iframe.
+ *
+ * @return array{0: string, 1: bool}|null The element and whether it gets a noscript copy, or null to leave it untouched.
+ */
+ private function lazyload_media_element( string $element, bool $is_iframe ): ?array {
+ if ( $is_iframe && strpos( $element, 'iframe' ) !== false ) {
+ return [ $this->replace_start_tag_src( $element, 'iframe', ' src="about:blank" data-opt-src' ), true ];
+ }
+ if ( $is_iframe || strpos( $element, 'video' ) === false ) {
+ return [ $element, true ];
+ }
+ if ( strpos( $element, 'source' ) === false ) {
+ return [ $this->replace_start_tag_src( $element, 'video', ' data-opt-src' ), true ];
+ }
+ if ( strpos( $element, 'preload' ) !== false ) {
+ return null;
+ }
+
+ return [ preg_replace( '#^((?: