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

Tdw 2277 decrease load time #121

Closed
wants to merge 9 commits into from
72 changes: 0 additions & 72 deletions scripts/delayed.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,9 @@ import {
decorateIcons,
fetchPlaceholders,
sampleRUM,
decorateBlock,
loadBlock,
loadScript,
getMetadata,
fetchGraphQL,
sendAnalyticsPageEvent,
} from './scripts.js';

const placeholders = await fetchPlaceholders();
Expand Down Expand Up @@ -646,75 +643,6 @@ async function populateStatusBar(statusBar) {

populateStatusBar(document.querySelector('header > .status-bar'));

/* setup cookie preferences */
function getCookie(cookieName) {
const name = `${cookieName}=`;
const decodedCookie = decodeURIComponent(document.cookie);
const split = decodedCookie.split(';');
// eslint-disable-next-line no-plusplus
for (let i = 0; i < split.length; i++) {
let c = split[i];
while (c.charAt(0) === ' ') c = c.substring(1);
if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
}
return null;
}

async function OptanonWrapper() {
const geoInfo = window.Optanon.getGeolocationData();
Object.keys(geoInfo).forEach((key) => {
const cookieName = `PGAT_${key.charAt(0).toUpperCase() + key.slice(1)}`;
const cookie = getCookie(cookieName);
if (!cookie || cookie !== geoInfo[key]) document.cookie = `${cookieName}=${geoInfo[key]}`;
});

const prevOptIn = localStorage.getItem('OptIn_PreviousPermissions');
if (prevOptIn) {
try {
const settings = JSON.parse(prevOptIn);
if (settings.tempImplied) {
localStorage.removeItem('OptIn_PreviousPermissions');
}
} catch (e) {
// eslint-disable-next-line no-console
console.error('OptIn_PreviousPermissions parse failed');
}
}
sendAnalyticsPageEvent();
}

const otId = placeholders.onetrustId;
if (otId) {
const cookieScript = loadScript('https://cdn.cookielaw.org/scripttemplates/otSDKStub.js');
cookieScript.setAttribute('data-domain-script', `${otId}${isProd ? '' : '-test'}`);
cookieScript.setAttribute('data-dlayer-name', 'dataLayer');
cookieScript.setAttribute('data-nscript', 'beforeInteractive');

const gtmId = placeholders.googletagmanagerId;
if (gtmId) {
const GTMScript = document.createElement('script');
GTMScript.innerHTML = `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','${gtmId}');`;
document.head.append(GTMScript);

const GTMFrame = document.createElement('no-script');
GTMFrame.innerHTML = `<iframe src="https://www.googletagmanager.com/ns.html?id=${gtmId}"
height="0" width="0" style="display:none;visibility:hidden"></iframe>`;
document.body.prepend(GTMFrame);
}

window.OptanonWrapper = OptanonWrapper;

if (document.querySelector('.marketing')) {
const marketingBlock = document.querySelector('.marketing');
decorateBlock(marketingBlock);
loadBlock(marketingBlock);
}
}

async function loadLiveChat() {
const liveChat = getMetadata('live-chat');
if (liveChat && ['yes', 'on', 'true'].includes(liveChat.toLowerCase())) {
Expand Down
78 changes: 78 additions & 0 deletions scripts/dependencies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// eslint-disable-next-line import/no-cycle
import {
decorateBlock,

Check failure on line 3 in scripts/dependencies.js

View workflow job for this annotation

GitHub Actions / build

Expected indentation of 2 spaces but found 4
fetchPlaceholders,

Check failure on line 4 in scripts/dependencies.js

View workflow job for this annotation

GitHub Actions / build

Expected indentation of 2 spaces but found 4
loadBlock,

Check failure on line 5 in scripts/dependencies.js

View workflow job for this annotation

GitHub Actions / build

Expected indentation of 2 spaces but found 4
loadScript,

Check failure on line 6 in scripts/dependencies.js

View workflow job for this annotation

GitHub Actions / build

Expected indentation of 2 spaces but found 4
} from './scripts.js';

const placeholders = await fetchPlaceholders();
const isProd = window.location.hostname.endsWith(placeholders.hostname);

/* setup cookie preferences */
function getCookie(cookieName) {
const name = `${cookieName}=`;

Check failure on line 14 in scripts/dependencies.js

View workflow job for this annotation

GitHub Actions / build

Expected indentation of 2 spaces but found 4
const decodedCookie = decodeURIComponent(document.cookie);

Check failure on line 15 in scripts/dependencies.js

View workflow job for this annotation

GitHub Actions / build

Expected indentation of 2 spaces but found 4
const split = decodedCookie.split(';');

Check failure on line 16 in scripts/dependencies.js

View workflow job for this annotation

GitHub Actions / build

Expected indentation of 2 spaces but found 4
// eslint-disable-next-line no-plusplus

Check failure on line 17 in scripts/dependencies.js

View workflow job for this annotation

GitHub Actions / build

Expected indentation of 2 spaces but found 4
for (let i = 0; i < split.length; i++) {

Check failure on line 18 in scripts/dependencies.js

View workflow job for this annotation

GitHub Actions / build

Expected indentation of 2 spaces but found 4
let c = split[i];

Check failure on line 19 in scripts/dependencies.js

View workflow job for this annotation

GitHub Actions / build

Expected indentation of 4 spaces but found 8
while (c.charAt(0) === ' ') c = c.substring(1);
if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
}
return null;
}

async function OptanonWrapper() {
const geoInfo = window.Optanon.getGeolocationData();
Object.keys(geoInfo).forEach((key) => {
const cookieName = `PGAT_${key.charAt(0).toUpperCase() + key.slice(1)}`;
const cookie = getCookie(cookieName);
if (!cookie || cookie !== geoInfo[key]) document.cookie = `${cookieName}=${geoInfo[key]}`;
});

const prevOptIn = localStorage.getItem('OptIn_PreviousPermissions');
if (prevOptIn) {
try {
const settings = JSON.parse(prevOptIn);
if (settings.tempImplied) {
localStorage.removeItem('OptIn_PreviousPermissions');
}
} catch (e) {
// eslint-disable-next-line no-console
console.error('OptIn_PreviousPermissions parse failed');
}
}
}

const otId = placeholders.onetrustId;
if (otId) {
const cookieScript = loadScript('https://cdn.cookielaw.org/scripttemplates/otSDKStub.js');
cookieScript.setAttribute('data-domain-script', `${otId}${isProd ? '' : '-test'}`);
cookieScript.setAttribute('data-dlayer-name', 'dataLayer');
cookieScript.setAttribute('data-nscript', 'beforeInteractive');

const gtmId = placeholders.googletagmanagerId;
if (gtmId) {
const GTMScript = document.createElement('script');
GTMScript.innerHTML = `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','${gtmId}');`;
document.head.append(GTMScript);

const GTMFrame = document.createElement('no-script');
GTMFrame.innerHTML = `<iframe src="https://www.googletagmanager.com/ns.html?id=${gtmId}"
height="0" width="0" style="display:none;visibility:hidden"></iframe>`;
document.body.prepend(GTMFrame);
}

window.OptanonWrapper = OptanonWrapper;

if (document.querySelector('.marketing')) {
const marketingBlock = document.querySelector('.marketing');
decorateBlock(marketingBlock);
loadBlock(marketingBlock);
}
}
68 changes: 17 additions & 51 deletions scripts/scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,8 @@ export function addPublishDependencies(url) {
*/
export function toClassName(name) {
return name && typeof name === 'string'
? name.toLowerCase().replace(/[^0-9a-z]/gi, '-')
: '';
? name.toLowerCase().replace(/[^0-9a-z]/gi, '-')
: '';
}

/*
Expand Down Expand Up @@ -250,15 +250,15 @@ export async function fetchPlaceholders(prefix = 'default') {
window.placeholders[`${prefix}-loaded`] = new Promise((resolve, reject) => {
try {
fetch(`${prefix === 'default' ? '' : prefix}/placeholders.json`)
.then((resp) => resp.json())
.then((json) => {
const placeholders = {};
json.data.forEach((placeholder) => {
placeholders[toCamelCase(placeholder.Key)] = placeholder.Text;
.then((resp) => resp.json())
.then((json) => {
const placeholders = {};
json.data.forEach((placeholder) => {
placeholders[toCamelCase(placeholder.Key)] = placeholder.Text;
});
window.placeholders[prefix] = placeholders;
resolve();
});
window.placeholders[prefix] = placeholders;
resolve();
});
} catch (e) {
// error loading placeholders
window.placeholders[prefix] = {};
Expand Down Expand Up @@ -403,8 +403,8 @@ export function updateSectionsStatus(main) {
*/
export function decorateBlocks(main) {
main
.querySelectorAll('div.section > div > div')
.forEach((block) => decorateBlock(block));
.querySelectorAll('div.section > div > div')
.forEach((block) => decorateBlock(block));
}

/**
Expand Down Expand Up @@ -632,13 +632,13 @@ export function decorateButtons(element) {
up.classList.add('button-container');
}
if (up.childNodes.length === 1 && up.tagName === 'STRONG'
&& twoup.childNodes.length === 1 && twoup.tagName === 'P') {
&& twoup.childNodes.length === 1 && twoup.tagName === 'P') {
a.className = 'button primary';
twoup.classList.add('button-container');
up.outerHTML = a.outerHTML;
}
if (up.childNodes.length === 1 && up.tagName === 'EM'
&& twoup.childNodes.length === 1 && twoup.tagName === 'P') {
&& twoup.childNodes.length === 1 && twoup.tagName === 'P') {
a.className = 'button secondary';
twoup.classList.add('button-container');
up.outerHTML = a.outerHTML;
Expand Down Expand Up @@ -787,8 +787,8 @@ function buildRelatedStoriesBlock(main, tags) {
const FULL_WIDTH_BLOCKS = ['carousel', 'carousel course', 'hero', 'news', 'player-feature', 'share', 'teaser', 'weather'];
const sections = main.querySelectorAll(':scope > div');
const nonFullWidthSection = [...sections]
.find((section) => ![...section.children] // check section
.find((child) => FULL_WIDTH_BLOCKS.includes(child.className))); // check content in section
.find((section) => ![...section.children] // check section
.find((child) => FULL_WIDTH_BLOCKS.includes(child.className))); // check content in section
let storiesSection = nonFullWidthSection;
if (!storiesSection) { // if no section without full-width content, create one
storiesSection = document.createElement('div');
Expand Down Expand Up @@ -1077,6 +1077,7 @@ async function loadLazy(doc) {
*/
function loadDelayed() {
// eslint-disable-next-line import/no-cycle
window.setTimeout(() => import('./dependencies.js'), 500);
window.setTimeout(() => import('./delayed.js'), 4000);
// load anything that can be postponed to the latest here
}
Expand Down Expand Up @@ -1122,41 +1123,6 @@ export function addHeaderSizing(block, classPrefix = 'heading', selector = 'h1,
});
}

function getPageNameAndSections() {
const pageSectionParts = window.location.pathname.split('/').filter((subPath) => subPath !== '');
const pageName = pageSectionParts.join(':');
const finalPageName = pageName === '' ? 'Home' : pageName;

return {
pageName: finalPageName,
sections: pageSectionParts,
};
}

export async function sendAnalyticsPageEvent() {
window.dataLayer = window.dataLayer || [];
const dl = window.dataLayer;
const placeholders = await fetchPlaceholders();
const isUserLoggedIn = window.gigyaAccountInfo && window.gigyaAccountInfo != null
&& window.gigyaAccountInfo.errorCode === 0;

const { pageName, sections } = getPageNameAndSections();
dl.push({
event: 'pageload',
pageName,
pageUrl: window.location.href,
siteSection: sections[0] || '',
siteSubSection: sections[1] || '',
siteSubSection2: sections[2] || '',
gigyaID: isUserLoggedIn && window.gigyaAccountInfo.UID ? window.gigyaAccountInfo.UID : '',
userLoggedIn: isUserLoggedIn ? 'Logged In' : 'Logged Out',
tourName: placeholders.tourName.toLowerCase().replaceAll(' ', '_'),
tournamentID: `${placeholders.tourCode.toUpperCase()}${placeholders.currentYear}${placeholders.tournamentId}`,
ipAddress: '127.0.0.1',
deviceType: 'Web',
});
}

try {
const hidden = Symbol('hidden');
const proxy = Symbol('proxy');
Expand Down
Loading