forked from adobe/aem-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 7
/
scripts.js
300 lines (268 loc) · 9.37 KB
/
scripts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/*
Copyright 2023 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
import {
sampleRUM,
buildBlock,
createOptimizedPicture as libCreateOptimizedPicture,
decorateButtons,
decorateIcons,
decorateSections,
decorateBlocks,
decorateTemplateAndTheme,
waitForLCP,
loadBlocks,
loadCSS,
} from './lib-franklin.js';
const LCP_BLOCKS = []; // add your LCP blocks to the list
/**
* Builds hero block and prepends to main in a new section.
* @param {Element} main The container element
*/
function buildHeroBlock(main) {
const h1 = main.querySelector('h1');
const picture = main.querySelector('picture');
// eslint-disable-next-line no-bitwise
if (h1 && picture && (h1.compareDocumentPosition(picture) & Node.DOCUMENT_POSITION_PRECEDING)) {
const section = document.createElement('div');
section.append(buildBlock('hero', { elems: [picture, h1] }));
main.prepend(section);
}
}
/**
* load fonts.css and set a session storage flag
*/
async function loadFonts() {
await loadCSS(`${window.hlx.codeBasePath}/styles/fonts.css`);
try {
if (!window.location.hostname.includes('localhost')) sessionStorage.setItem('fonts-loaded', 'true');
} catch (e) {
// do nothing
}
}
/**
* Builds all synthetic blocks in a container element.
* @param {Element} main The container element
*/
function buildAutoBlocks(main) {
try {
buildHeroBlock(main);
} catch (error) {
// eslint-disable-next-line no-console
console.error('Auto Blocking failed', error);
}
}
/**
* Gets the extension of a URL.
* @param {string} url The URL
* @returns {string} The extension
* @private
* @example
* get_url_extension('https://example.com/foo.jpg');
* // returns 'jpg'
* get_url_extension('https://example.com/foo.jpg?bar=baz');
* // returns 'jpg'
* get_url_extension('https://example.com/foo');
* // returns ''
* get_url_extension('https://example.com/foo.jpg#qux');
* // returns 'jpg'
*/
function getUrlExtension(url) {
return url.split(/[#?]/)[0].split('.').pop().trim();
}
/**
* Checks if an element is an external image.
* @param {Element} element The element
* @param {string} externalImageMarker The marker for external images
* @returns {boolean} Whether the element is an external image
* @private
*/
function isExternalImage(element, externalImageMarker) {
// if the element is not an anchor, it's not an external image
if (element.tagName !== 'A') return false;
// if the element is an anchor with the external image marker as text content,
// it's an external image
if (element.textContent.trim() === externalImageMarker) {
return true;
}
// if the element is an anchor with the href as text content and the href has
// an image extension, it's an external image
if (element.textContent.trim() === element.getAttribute('href')) {
const ext = getUrlExtension(element.getAttribute('href'));
return ext && ['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(ext.toLowerCase());
}
}
/*
* Appends query params to a URL
* @param {string} url The URL to append query params to
* @param {object} params The query params to append
* @returns {string} The URL with query params appended
* @private
* @example
* appendQueryParams('https://example.com', { foo: 'bar' });
* // returns 'https://example.com?foo=bar'
*/
function appendQueryParams(url, params) {
const { searchParams } = url;
params.forEach((value, key) => {
searchParams.set(key, value);
});
url.search = searchParams.toString();
return url.toString();
}
/**
* Creates an optimized picture element for an image.
* If the image is not an absolute URL, it will be passed to libCreateOptimizedPicture.
* @param {string} src The image source URL
* @param {string} alt The image alt text
* @param {boolean} eager Whether to load the image eagerly
* @param {object[]} breakpoints The breakpoints to use
* @returns {Element} The picture element
*
*/
export function createOptimizedPicture(src, alt = '', eager = false, breakpoints = [{ media: '(min-width: 600px)', width: '2000' }, { width: '750' }]) {
const isAbsoluteUrl = /^https?:\/\//i.test(src);
// Fallback to createOptimizedPicture if src is not an absolute URL
if (!isAbsoluteUrl) return libCreateOptimizedPicture(src, alt, eager, breakpoints);
const url = new URL(src);
const picture = document.createElement('picture');
const { pathname } = url;
const ext = pathname.substring(pathname.lastIndexOf('.') + 1);
// webp
breakpoints.forEach((br) => {
const source = document.createElement('source');
if (br.media) source.setAttribute('media', br.media);
source.setAttribute('type', 'image/webp');
const searchParams = new URLSearchParams({ width: br.width, format: 'webply' });
source.setAttribute('srcset', appendQueryParams(url, searchParams));
picture.appendChild(source);
});
// fallback
breakpoints.forEach((br, i) => {
const searchParams = new URLSearchParams({ width: br.width, format: ext });
if (i < breakpoints.length - 1) {
const source = document.createElement('source');
if (br.media) source.setAttribute('media', br.media);
source.setAttribute('srcset', appendQueryParams(url, searchParams));
picture.appendChild(source);
} else {
const img = document.createElement('img');
img.setAttribute('loading', eager ? 'eager' : 'lazy');
img.setAttribute('alt', alt);
picture.appendChild(img);
img.setAttribute('src', appendQueryParams(url, searchParams));
}
});
return picture;
}
/*
* Decorates external images with a picture element
* @param {Element} ele The element
* @param {string} deliveryMarker The marker for external images
* @private
* @example
* decorateExternalImages(main, '//External Image//');
*/
function decorateExternalImages(ele, deliveryMarker) {
const extImages = ele.querySelectorAll('a');
extImages.forEach((extImage) => {
if (isExternalImage(extImage, deliveryMarker)) {
const extImageSrc = extImage.getAttribute('href');
const extPicture = createOptimizedPicture(extImageSrc);
/* copy query params from link to img */
const extImageUrl = new URL(extImageSrc);
const { searchParams } = extImageUrl;
extPicture.querySelectorAll('source, img').forEach((child) => {
if (child.tagName === 'SOURCE') {
const srcset = child.getAttribute('srcset');
if (srcset) {
child.setAttribute('srcset', appendQueryParams(new URL(srcset, extImageSrc), searchParams));
}
} else if (child.tagName === 'IMG') {
const src = child.getAttribute('src');
if (src) {
child.setAttribute('src', appendQueryParams(new URL(src, extImageSrc), searchParams));
}
}
});
extImage.parentNode.replaceChild(extPicture, extImage);
}
});
}
/**
* Decorates the main element.
* @param {Element} main The main element
*/
// eslint-disable-next-line import/prefer-default-export
export function decorateMain(main) {
// decorate external images with explicit external image marker
decorateExternalImages(main, '//External Image//');
// decorate external images with implicit external image marker
decorateExternalImages(main);
// hopefully forward compatible button decoration
decorateButtons(main);
decorateIcons(main);
buildAutoBlocks(main);
decorateSections(main);
decorateBlocks(main);
}
/**
* Loads everything needed to get to LCP.
* @param {Element} doc The container element
*/
async function loadEager(doc) {
document.documentElement.lang = 'en';
decorateTemplateAndTheme();
const main = doc.querySelector('main');
if (main) {
decorateMain(main);
document.body.classList.add('appear');
await waitForLCP(LCP_BLOCKS);
}
try {
/* if desktop (proxy for fast connection) or fonts already loaded, load fonts.css */
if (window.innerWidth >= 900 || sessionStorage.getItem('fonts-loaded')) {
loadFonts();
}
} catch (e) {
// do nothing
}
}
/**
* Loads everything that doesn't need to be delayed.
* @param {Element} doc The container element
*/
async function loadLazy(doc) {
const main = doc.querySelector('main');
await loadBlocks(main);
const { hash } = window.location;
const element = hash ? doc.getElementById(hash.substring(1)) : false;
if (hash && element) element.scrollIntoView();
loadCSS(`${window.hlx.codeBasePath}/styles/lazy-styles.css`);
loadFonts();
sampleRUM('lazy');
sampleRUM.observe(main.querySelectorAll('div[data-block-name]'));
sampleRUM.observe(main.querySelectorAll('picture > img'));
}
/**
* Loads everything that happens a lot later,
* without impacting the user experience.
*/
function loadDelayed() {
// eslint-disable-next-line import/no-cycle
window.setTimeout(() => import('./delayed.js'), 3000);
// load anything that can be postponed to the latest here
}
async function loadPage() {
await loadEager(document);
await loadLazy(document);
loadDelayed();
}
loadPage();