docbrown/app/javascript/packs/billboard.js
Ben Halpern 51a2292fbd
Fix display ad event race condition (#19326)
* Mitigate race condition for async loaded billboard

* Put observeDisplayAds in billboard.js
2023-04-13 18:30:46 -04:00

34 lines
1.1 KiB
JavaScript

import { setupDisplayAdDropdown } from '../utilities/displayAdDropdown';
// the term billboard can be synonymously interchanged with displayAd
async function getBillboard() {
const placeholderElements = document.getElementsByClassName(
'js-display-ad-container',
);
const promises = [...placeholderElements].map(generateDisplayAd);
await Promise.all(promises);
}
async function generateDisplayAd(element) {
const { asyncUrl } = element.dataset;
if (asyncUrl) {
const response = await window.fetch(`${asyncUrl}`);
const htmlContent = await response.text();
const generatedElement = document.createElement('div');
generatedElement.innerHTML = htmlContent;
element.innerHTML = '';
element.appendChild(generatedElement);
setupDisplayAdDropdown();
// This is called here because the ad is loaded asynchronously.
// The original code is still in the asset pipeline, so is not importable.
// This could be refactored to be importable as we continue that migration.
// eslint-disable-next-line no-undef
observeDisplayAds();
}
}
getBillboard();