This repository was archived by the owner on Mar 8, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathonion-loader-dev.js
More file actions
260 lines (244 loc) · 8.3 KB
/
onion-loader-dev.js
File metadata and controls
260 lines (244 loc) · 8.3 KB
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
import jsAssetList from "./jsAssets.mjs";
const fallbackAssetArray = jsAssetList.dynamicAssets;
/* eslint-disable no-use-before-define */
/* eslint-disable no-console */
//*** Lazyloader ***//
/**
* The options object for the lazyloader.
* @type {object}
* @property {string} rootMargin The root margin for the IntersectionObserver.
* @default '0% 0% 0%'
* @property {number} threshold The threshold for the IntersectionObserver.
* @property {boolean} debugLogMessages Whether to log debug messages.
* @property {array} lazyBlocksToSearchFor The array of lazy blocks to search for.
* @property {array} lazyBlocksFound The array of lazy blocks found.
* @property {array} assetArray The array of assets to load.
* @property {object} assetMap The asset map object.
* @property {boolean} ignoreCss Whether to ignore the css.
* @property {boolean} lazy Whether to lazy load the assets (after Assets alias).
* @property {string} filePath The file path for the js assets.
* @default 'js/blocks/'
* @property {string} filePathCss The file path for the css assets (after Assets alias).
* @default 'scss/blocks/'
*/
const options = {
rootMargin: "100% 0px 300px 0px",
threshold: 0,
debugLogMessages: false,
lazyBlocksToSearchFor: [],
lazyBlocksFound: [],
assetArray: fallbackAssetArray, //latest assetArray can be found in /@total_onion/onion-library/public/jsAssets.mjs
assetMap: {},
css: true,
lazy: true,
cssLoadingStyle: "component", // 'component' or 'bundle'
filePrefix: "dev", //'nodemodules', 'assets' or 'dev'
fileSuffixJs: ".js",
fileSuffixCss: ".scss",
filePath: "js/blocks",
filePathCss: "scss/blocks",
};
/**
* Initializes the lazyloader.
*/
function lazyloaderInit() {
options.debugLogMessages && console.log("Lazy Loader initialized!");
options.lazyBlocksToSearchFor = [];
options.assetArray.forEach((asset) => {
// if (options.filePrefix === "nodemodules") {
// options.assetMap[asset.assetKey] = {
// js: () =>
// import(
// `NodeModules/@total_onion/onion-library/components/block-${asset.assetKey}/${asset.assetKey}${options.fileSuffixJs}`
// ),
// css: options.ignoreCss === true,
// };
// }
// if (options.filePrefix === "assets") {
// options.assetMap[asset.assetKey] = {
// js: () => import(`Assets/${this.options.filePath}/${asset.assetKey}`),
// css: options.ignoreCss === false,
// };
// }
if (options.filePrefix === "dev") {
options.assetMap[asset.assetKey] = {
js: () =>
import(
`../../../../../../../../onion-library/components/block-${asset.assetKey}/${asset.assetKey}${options.fileSuffixJs}`
),
css: options.ignoreCss === true,
};
}
// Add to lazy blocks to search for
options.lazyBlocksToSearchFor.push(`[data-assetkey="${asset.assetKey}"]`);
options.lazyBlocksFound = Array.from(
document.querySelectorAll(options.lazyBlocksToSearchFor)
);
});
// If data eager loading attribute is true - load js straight away
options.lazyBlocksFound.forEach((block) => {
if (block.dataset.eager == "true") {
callBlockJs(block);
}
});
options.debugLogMessages && console.log("Lazyloader Options", options);
// Check if the browser has intersection observer which is needed for the Lazyloader or if all assets should load immediately anyway.
if (options.lazy === false || !("IntersectionObserver" in window)) {
options.debugLogMessages && console.log("running eager loading");
try {
options.lazyBlocksFound.forEach((block) => {
callBlockJs(block);
});
} catch (error) {
console.log(error);
}
} else {
options.debugLogMessages && console.log("running normal process");
observerInit(options.lazyBlocksFound);
}
}
/**
* Initializes the IntersectionObserver for the lazy loading of blocks.
* @param {array} elementsToObserve The array of block elements to observe.
*/
function observerInit(elementsToObserve = []) {
const observer = new IntersectionObserver(intersectionCallback, options);
elementsToObserve.forEach((element) => {
if (element) {
observer.observe(element);
}
});
}
/**
* Callback function for the IntersectionObserver.
* @param {array} entries The entries array from the IntersectionObserver.
* @param {object} observer The IntersectionObserver object.
*/
const intersectionCallback = (entries, observer) => {
options.debugLogMessages && console.log("Observer entries", entries);
entries.forEach((entry) => {
if (entry.isIntersecting) {
const lazyTarget = entry.target;
try {
callBlockJs(lazyTarget);
} catch (error) {
console.log(
error,
"block data assetkey:",
lazyTarget.dataset.assetkey,
" - ",
"asset import function:",
options.assetMap[lazyTarget.dataset.assetkey],
"are you missing an asset key or import function?"
);
}
observer.unobserve(lazyTarget);
options.debugLogMessages &&
console.log("Unobserving lazyElement", lazyTarget);
}
});
};
/**
* Calls the block asset functions and adds the loaded class to the block.
* @param {object} block The block element.
*/
function callBlockJs(block) {
if (!block.classList.contains("loaded")) {
Promise.all([
options.assetMap[block.dataset.assetkey].js(),
loadCss(block.dataset.assetkey),
]).then((module) => {
try {
if (block.dataset.jsload !== "false") {
module[0].default({
block,
css: false,
});
} else {
options.debugLogMessages &&
console.log(
`Skipping JS load for block: ${block.dataset.assetkey}`
);
}
block.classList.add("loaded");
} catch (error) {
console.log("could not load block js", error);
}
});
}
}
/**
* Checks to see if the css for the block has already been included in the 'criticalconfig' window object.
* Will return true if it is.
* @param {string} assetKey The assetkey string of the block.
* @returns {boolean}
*/
export function inCriticalCssConfig(assetKey) {
if (!globalThis.criticalConfig) {
return false;
}
if (
globalThis.criticalConfig &&
globalThis.criticalConfig.indexOf(assetKey) === -1
) {
return false;
}
return true;
}
/**
* Dynamically loads the css for the block if it has not already been included in critical css or the css property is set to false.
* @param {string} assetKey The assetkey string of the block.
* @param {object} options The options object which will at the very least contain the css property set to true.
* @returns {promise}
*/
export function loadCss(assetKey) {
// if (options.css == true && options.cssLoadingStyle === "bundle") {
// options.debugLogMessages && console.log("using css bundle");
// const promise = new Promise((resolve) => {
// import(
// `NodeModules/@total_onion/onion-library/public/publicbundlecss.css`
// ).then(() => {
// console.log("resolved");
// resolve(true);
// });
// });
// return promise;
// }
// if (
// options.css == true &&
// options.cssLoadingStyle === "component" &&
// options.filePrefix === "nodemodules"
// ) {
// options.debugLogMessages && console.log("using individual css");
// const promise = new Promise((resolve) => {
// if (options.css === true && !inCriticalCssConfig(assetKey)) {
// import(
// /* webpackChunkName: "[request]" */ `NodeModules/@total_onion/onion-library/components/block-${assetKey}/${assetKey}${options.fileSuffixCss}`
// ).then(() => resolve(true));
// } else {
// return resolve(true);
// }
// });
// }
if (
options.css == true &&
options.cssLoadingStyle === "component" &&
options.filePrefix === "dev"
) {
options.debugLogMessages && console.log("using dev css");
const promise = new Promise((resolve) => {
if (options.css === true && !inCriticalCssConfig(assetKey)) {
import(
`../../../../../../../../onion-library/components/block-${assetKey}/${assetKey}${options.fileSuffixCss}`
).then(() => resolve(true));
} else {
return resolve(true);
}
});
}
}
const api = {
lazyloaderInit,
options,
};
export default api;