diff --git a/scripts/scripts.js b/scripts/scripts.js index 1e206db924..9c2369fa0a 100644 --- a/scripts/scripts.js +++ b/scripts/scripts.js @@ -10,10 +10,36 @@ import { waitForLCP, loadBlocks, loadCSS, + toClassName, + getMetadata, + loadScript, + toCamelCase, } from './aem.js'; const LCP_BLOCKS = []; // add your LCP blocks to the list +const AUDIENCES = { + mobile: () => window.innerWidth < 600, + desktop: () => window.innerWidth >= 600, + // define your custom audiences here as needed +}; + +/** + * Gets all the metadata elements that are in the given scope. + * @param {String} scope The scope/prefix for the metadata + * @returns an array of HTMLElement nodes that match the given scope + */ +export function getAllMetadata(scope) { + return [...document.head.querySelectorAll(`meta[property^="${scope}:"],meta[name^="${scope}-"]`)] + .reduce((res, meta) => { + const id = toClassName(meta.name + ? meta.name.substring(scope.length + 1) + : meta.getAttribute('property').split(':')[1]); + res[id] = meta.getAttribute('content'); + return res; + }, {}); +} + /** * Moves all the attributes from a given elmenet to another given element. * @param {Element} from the element to copy attributes from @@ -87,6 +113,22 @@ export function decorateMain(main) { decorateBlocks(main); } +// Define an execution context +const pluginContext = { + getAllMetadata, + getMetadata, + loadCSS, + loadScript, + sampleRUM, + toCamelCase, + toClassName, +}; + +const experimentationOptions = { + audiences: AUDIENCES, + isProd: () => !window.location.hostname.endsWith('.page'), +}; + /** * Loads everything needed to get to LCP. * @param {Element} doc The container element @@ -94,6 +136,15 @@ export function decorateMain(main) { async function loadEager(doc) { document.documentElement.lang = 'en'; decorateTemplateAndTheme(); + + if (getMetadata('experiment') + || Object.keys(getAllMetadata('campaign')).length + || Object.keys(getAllMetadata('audience')).length) { + // eslint-disable-next-line import/no-relative-packages + const { loadEager: runEager } = await import('../plugins/experimentation/src/index.js'); + await runEager(document, experimentationOptions, pluginContext); + } + const main = doc.querySelector('main'); if (main) { decorateMain(main); @@ -132,6 +183,14 @@ async function loadLazy(doc) { sampleRUM('lazy'); sampleRUM.observe(main.querySelectorAll('div[data-block-name]')); sampleRUM.observe(main.querySelectorAll('picture > img')); + + if ((getMetadata('experiment') + || Object.keys(getAllMetadata('campaign')).length + || Object.keys(getAllMetadata('audience')).length)) { + // eslint-disable-next-line import/no-relative-packages + const { loadLazy: runLazy } = await import('../plugins/experimentation/src/index.js'); + await runLazy(document, experimentationOptions, pluginContext); + } } /**