forked from shubhamjain/svg-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsvg-loader.js
362 lines (301 loc) · 9.53 KB
/
svg-loader.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
"use strict";
const cssScope = require("./lib/scope-css");
const cssUrlFixer = require("./lib/css-url-fixer");
const counter = require("./lib/counter");
const { getStorage } = require("./lib/storage");
const STORAGE_NAME = "svg-loader-cache";
const isCacheAvailable = async (url) => {
try {
const storage = await getStorage(STORAGE_NAME);
let item = await storage.getItem(`loader_${url}`);
if (!item) {
return;
}
item = JSON.parse(item);
if (Date.now() < item.expiry) {
return item.data;
} else {
storage.removeItem(`loader_${url}`);
return;
}
} catch (e) {
return;
}
};
const setCache = async (url, data, cacheOpt) => {
try {
const storage = await getStorage(STORAGE_NAME);
const cacheExp = parseInt(cacheOpt, 10);
await storage.setItem(
`loader_${url}`,
JSON.stringify({
data,
expiry:
Date.now() +
(Number.isNaN(cacheExp) ? 60 * 60 * 1000 * 24 : cacheExp),
})
);
} catch (e) {
console.error(e);
}
};
const DOM_EVENTS = [];
const getAllEventNames = () => {
if (DOM_EVENTS.length) {
return DOM_EVENTS;
}
for (const prop in document.head) {
if (prop.startsWith("on")) {
DOM_EVENTS.push(prop);
}
}
return DOM_EVENTS;
};
const attributesSet = {};
const renderBody = (elem, options, body) => {
const { enableJs, disableUniqueIds, disableCssScoping } = options;
const parser = new DOMParser();
const doc = parser.parseFromString(body, "text/html");
const fragment = doc.querySelector("svg");
const eventNames = getAllEventNames();
// When svg-loader is loading in the same element, it's
// important to keep track of original properties.
const elemAttributesSet =
attributesSet[elem.getAttribute("data-id")] || new Set();
const elemUniqueId =
elem.getAttribute("data-id") || `svg-loader_${counter.incr()}`;
const idMap = {};
if (!disableUniqueIds) {
// Append a unique suffix for every ID so elements don't conflict.
Array.from(doc.querySelectorAll("[id]")).forEach((elem) => {
const id = elem.getAttribute("id");
const newId = `${id}_${counter.incr()}`;
elem.setAttribute("id", newId);
idMap[id] = newId;
});
}
Array.from(doc.querySelectorAll("*")).forEach((elem) => {
// Unless explicitly set, remove JS code (default)
if (elem.tagName === "script") {
if (!enableJs) {
elem.remove();
return;
} else {
const scriptEl = document.createElement("script");
scriptEl.innerHTML = elem.innerHTML;
document.body.appendChild(scriptEl);
}
}
for (let i = 0; i < elem.attributes.length; i++) {
const { name, value } = elem.attributes[i];
const newValue = cssUrlFixer(idMap, value, name);
if (value !== newValue) {
elem.setAttribute(name, newValue);
}
// Remove event functions: onmouseover, onclick ... unless specifically enabled
if (eventNames.includes(name.toLowerCase()) && !enableJs) {
elem.removeAttribute(name);
continue;
}
// Remove "javascript:..." unless specifically enabled
if (
["href", "xlink:href"].includes(name) &&
value.startsWith("javascript") &&
!enableJs
) {
elem.removeAttribute(name);
}
}
// .first -> [data-id="svg_loader_341xx"] .first
// Makes sure that class names don't conflict with each other.
if (elem.tagName === "style" && !disableCssScoping) {
let newValue = cssScope(
elem.innerHTML,
`[data-id="${elemUniqueId}"]`,
idMap
);
newValue = cssUrlFixer(idMap, newValue);
if (newValue !== elem.innerHTML) elem.innerHTML = newValue;
}
});
for (let i = 0; i < fragment.attributes.length; i++) {
const { name, value } = fragment.attributes[i];
// Don't override the attributes already defined, but override the ones that
// were in the original element
if (!elem.getAttribute(name) || elemAttributesSet.has(name)) {
elemAttributesSet.add(name);
elem.setAttribute(name, value);
}
}
attributesSet[elemUniqueId] = elemAttributesSet;
elem.setAttribute("data-id", elemUniqueId);
elem.innerHTML = fragment.innerHTML;
const event = new CustomEvent("iconload", {
bubbles: true,
});
elem.dispatchEvent(event);
if (elem.getAttribute("oniconload")) {
// Handling (and executing) event attribute for our event (oniconload)
// isn't straightforward. Because a) the code is a raw string b) there's
// no way to specify the context for execution. So, `this` in the attribute
// will point to `window` instead of the element itself.
//
// Here we are recycling a rarely used GlobalEventHandler 'onloadedmetadata'
// and offloading the execution to the browser. This is a hack, but because
// the event doesn't bubble, it shouldn't affect anything else in the code.
elem.setAttribute("onloadedmetadata", elem.getAttribute("oniconload"));
const event = new CustomEvent("loadedmetadata", {
bubbles: false,
});
elem.dispatchEvent(event);
elem.removeAttribute("onloadedmetadata");
}
};
const requestsInProgress = {};
const memoryCache = {};
const renderIcon = async (elem) => {
const src = elem.getAttribute("data-src");
const cacheOpt = elem.getAttribute("data-cache");
const enableJs = elem.getAttribute("data-js") === "enabled";
const disableUniqueIds = elem.getAttribute("data-unique-ids") === "disabled";
const disableCssScoping =
elem.getAttribute("data-css-scoping") === "disabled";
let lsCache = null;
const memCacheHit = memoryCache[src];
// if not in memory, request from IndexedDB
if (!memCacheHit) {
lsCache = await isCacheAvailable(src);
}
const isCachingEnabled = cacheOpt !== "disabled";
const renderBodyCb = renderBody.bind(self, elem, {
enableJs,
disableUniqueIds,
disableCssScoping,
});
// Memory cache optimizes same icon requested multiple times on the page
if (memCacheHit || (isCachingEnabled && lsCache)) {
const cache = memCacheHit || lsCache;
// store the entry to memory cache if not there yet
if (!memCacheHit) {
memoryCache[src] = cache;
}
renderBodyCb(cache);
} else {
// If the same icon is being requested to rendered
// avoid firing multiple XHRs
if (requestsInProgress[src]) {
setTimeout(() => renderIcon(elem), 20);
return;
}
requestsInProgress[src] = true;
fetch(src)
.then((response) => {
if (!response.ok) {
throw Error(
`Request for '${src}' returned ${response.status} (${response.statusText})`
);
}
return response.text();
})
.then((body) => {
const bodyLower = body.toLowerCase().trim();
if (!(bodyLower.startsWith("<svg") || bodyLower.startsWith("<?xml"))) {
throw Error(`Resource '${src}' returned an invalid SVG file`);
}
if (isCachingEnabled) {
setCache(src, body, cacheOpt);
}
memoryCache[src] = body;
renderBodyCb(body);
})
.catch((e) => {
console.error(e);
})
.finally(() => {
delete requestsInProgress[src];
});
}
};
let intObserver;
if (globalThis.IntersectionObserver) {
intObserver = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
renderIcon(entry.target);
// Unobserve as soon as soon the icon is rendered
intObserver.unobserve(entry.target);
}
});
},
{
// Keep high root margin because intersection observer
// can be slow to react
rootMargin: "1200px",
}
);
}
const handled = [];
function renderAllSVGs() {
if (typeof document === 'undefined') {
return
}
Array.from(document.querySelectorAll("svg[data-src]:not([data-id])")).forEach(
(element) => {
if (handled.indexOf(element) !== -1) {
return;
}
handled.push(element);
if (element.getAttribute("data-loading") === "lazy") {
intObserver.observe(element);
} else {
renderIcon(element);
}
}
);
}
let observerAdded = false;
const addObservers = () => {
if (observerAdded) {
return;
}
observerAdded = true;
const observer = new MutationObserver((mutationRecords) => {
const shouldTriggerRender = mutationRecords.some((record) =>
Array.from(record.addedNodes).some(
(elem) =>
elem.nodeType === Node.ELEMENT_NODE &&
((elem.getAttribute("data-src") && !elem.getAttribute("data-id")) || // Check if the element needs to be rendered
elem.querySelector("svg[data-src]:not([data-id])")) // Check if any of the element's children need to be rendered
)
);
// If any node is added, render all new nodes because the nodes that have already
// been rendered won't be rendered again.
if (shouldTriggerRender) {
renderAllSVGs();
}
// If data-src is changed, re-render
mutationRecords.forEach((record) => {
if (record.type === "attributes") {
renderIcon(record.target);
}
});
});
observer.observe(document.documentElement, {
attributeFilter: ["data-src"],
attributes: true,
childList: true,
subtree: true,
});
};
if (globalThis.addEventListener) {
// Start rendering SVGs as soon as possible
const intervalCheck = setInterval(() => {
renderAllSVGs();
}, 100);
globalThis.addEventListener("DOMContentLoaded", () => {
clearInterval(intervalCheck);
renderAllSVGs();
addObservers();
});
}