Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Core: suspend auctions during prerendering #12763

Merged
merged 4 commits into from
Feb 20, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions src/prebid.js
Original file line number Diff line number Diff line change
Expand Up @@ -569,13 +569,17 @@ pbjsInstance.requestBids = (function() {
})
}, 'requestBids');

return wrapHook(delegate, function requestBids(req = {}) {
return wrapHook(delegate, delayIfPrerendering(function requestBids(req = {}) {
// unlike the main body of `delegate`, this runs before any other hook has a chance to;
// it's also not restricted in its return value in the way `async` hooks are.

// Note that we delay this when prerendering because in some configurations requestBids may happen outside of
// pbjs.que (e.g. NPM consumers).

// if the request does not specify adUnits, clone the global adUnit array;
// otherwise, if the caller goes on to use addAdUnits/removeAdUnits, any asynchronous logic
// in any hook might see their effects.

let adUnits = req.adUnits || pbjsInstance.adUnits;
req.adUnits = (isArray(adUnits) ? adUnits.slice() : [adUnits]);

Expand All @@ -584,7 +588,7 @@ pbjsInstance.requestBids = (function() {
req.defer = defer({promiseFactory: (r) => new Promise(r)})
delegate.call(this, req);
return req.defer.promise;
});
}));
})();

export const startAuction = hook('async', function ({ bidsBackHandler, timeout: cbTimeout, adUnits, ttlBuffer, adUnitCodes, labels, auctionId, ortb2Fragments, metrics, defer } = {}) {
Expand Down Expand Up @@ -1018,16 +1022,36 @@ function processQueue(queue) {
});
}

/**
* Returns a wrapper around fn that delays execution until the page if activated, if it was prerendered.
* https://developer.chrome.com/docs/web-platform/prerender-pages
*/
function delayIfPrerendering(fn) {
return function () {
if (document.prerendering && !(config.getConfig('allowPrerendering') || getGlobal().allowPrerendering)) {
const that = this;
const args = Array.from(arguments);
return new Promise((resolve) => {
document.addEventListener('prerenderingchange', () => {
logInfo(`Auctions are suspended while page is prerendering. Set $$PREBID_GLOBAL$$.allowPrerendering = true to allow auctions during prerendering.`)
resolve(fn.apply(that, args))
}, {once: true})
})
} else {
return Promise.resolve(fn.apply(this, arguments));
}
}
}
/**
* @alias module:pbjs.processQueue
*/
pbjsInstance.processQueue = function () {
pbjsInstance.processQueue = delayIfPrerendering(function () {
pbjsInstance.que.push = pbjsInstance.cmd.push = quePush;
insertLocatorFrame();
hook.ready();
processQueue(pbjsInstance.que);
processQueue(pbjsInstance.cmd);
};
});
Copy link

@marco-prontera marco-prontera Feb 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @dgirardi I have a question, since now the processQueue is called when the prebid instance is ready, introducing this change will introduce the delay of all the queues, right?

I understood that the delay was actually only related to the requestBids, and this seems fantastic because we can execute everything in the prerendering "phase" and then firing only the auctions when the user actually views the page.
Can you tell me if I'm wrong? Sorry in advance.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a good suggestion. I defaulted to delaying everything because it seemed safer, but we couldn't think of an example of something that would break if we delayed only auctions. Updated.


/**
* @alias module:pbjs.triggerBilling
Expand Down
81 changes: 74 additions & 7 deletions test/spec/unit/pbjs_api_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -244,14 +244,81 @@ describe('Unit: Prebid Module', function () {
});

['cmd', 'que'].forEach(prop => {
it(`should patch ${prop}.push`, () => {
$$PREBID_GLOBAL$$[prop].push = false;
$$PREBID_GLOBAL$$.processQueue();
let ran = false;
$$PREBID_GLOBAL$$[prop].push(() => { ran = true; });
expect(ran).to.be.true;
describe(`using .${prop}`, () => {
let queue, ran;
beforeEach(() => {
ran = false;
queue = $$PREBID_GLOBAL$$[prop] = [];
});
after(() => {
$$PREBID_GLOBAL$$.processQueue();
})

function pushToQueue() {
queue.push(() => { ran = true });
}

it(`should patch .push`, () => {
$$PREBID_GLOBAL$$.processQueue();
pushToQueue();
expect(ran).to.be.true;
});

describe('when document is prerendering', () => {
before(() => {
if (!('prerendering' in document)) {
document.prerendering = null;
after(() => {
delete document.prerendering;
})
}
})
beforeEach(() => {
sandbox.stub(document, 'prerendering').get(() => true);
});
function prerenderingDone() {
document.dispatchEvent(new Event('prerenderingchange'));
}
it('should process queue only after prerenderingchange event', async () => {
pushToQueue();
$$PREBID_GLOBAL$$.processQueue();
pushToQueue();
expect(ran).to.be.false;
prerenderingDone();
expect(ran).to.be.true;
});

Object.entries({
'setConfig({allowPrerendering: true})': {
setup() {
$$PREBID_GLOBAL$$.setConfig({allowPrerendering: true});
},
teardown() {
$$PREBID_GLOBAL$$.setConfig({allowPrerendering: false});
}
},
'$$PREBID_GLOBAL$$.allowPrerendering = true': {
setup() {
$$PREBID_GLOBAL$$.allowPrerendering = true;
},
teardown() {
delete $$PREBID_GLOBAL$$.allowPrerendering;
}
}
}).forEach(([t, {setup, teardown}]) => {
describe(`with ${t}`, () => {
beforeEach(setup);
afterEach(teardown);
it('should process immediately', () => {
pushToQueue();
$$PREBID_GLOBAL$$.processQueue();
expect(ran).to.be.true;
})
})
})
})
})
})
});
})

describe('and global adUnits', () => {
Expand Down