Skip to content

Commit 90c3117

Browse files
authored
Merge pull request #76 from dewanakl/improve-lcp
feat: rewrite cache fonts
2 parents 0b2964a + d330228 commit 90c3117

1 file changed

Lines changed: 13 additions & 28 deletions

File tree

js/libs/loader.js

Lines changed: 13 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -69,38 +69,23 @@ const loadConfetti = (c) => {
6969
const loadAdditionalFont = (c) => {
7070

7171
const fonts = [
72-
'https://fonts.googleapis.com/css2?family=Sacramento&display=swap',
73-
'https://fonts.googleapis.com/css2?family=Noto+Naskh+Arabic&display=swap',
72+
{ css: 'https://fonts.googleapis.com/css2?family=Sacramento&display=swap', family: 'Sacramento' },
73+
{ css: 'https://fonts.googleapis.com/css2?family=Noto+Naskh+Arabic&display=swap', family: 'Noto Naskh Arabic' },
7474
];
7575

7676
/**
77-
* @param {string} font
77+
* @param {object}
7878
* @returns {Promise<void>}
7979
*/
80-
const loadFont = (font) => c.get(font)
81-
.then(window.fetch)
82-
.then((r) => r.text())
83-
.then((txt) => {
84-
const urls = Array.from(new Set(txt.matchAll(/url\(["']?([^"')]+)["']?\)/g)), (v) => v[1]);
85-
86-
return Promise.all(urls.map((v) => c.get(v))).then((res) => {
87-
88-
for (const [i, abs] of res.entries()) {
89-
txt = txt.replaceAll(urls[i], abs);
90-
}
91-
92-
return txt;
93-
});
94-
})
95-
.then((txt) => new Promise((res, rej) => {
96-
const link = document.createElement('link');
97-
link.onload = res;
98-
link.onerror = rej;
99-
100-
link.rel = 'stylesheet';
101-
link.href = URL.createObjectURL(new Blob([txt]));
102-
document.head.appendChild(link);
103-
}));
80+
const loadFont = ({ css, family }) => c.get(css).then((uri) => new Promise((res, rej) => {
81+
const link = document.createElement('link');
82+
link.onload = res;
83+
link.onerror = rej;
84+
85+
link.rel = 'stylesheet';
86+
link.href = uri;
87+
document.head.appendChild(link);
88+
})).then(() => document.fonts.load(`1em "${family}"`));
10489

10590
return Promise.all(fonts.map(loadFont));
10691
};
@@ -113,7 +98,7 @@ const loadAdditionalFont = (c) => {
11398
* @returns {Promise<void>}
11499
*/
115100
export const loader = (opt = {}) => {
116-
const c = cache('libs');
101+
const c = cache('libs').withForceCache();
117102

118103
return c.open().then(() => {
119104
const promises = [];

0 commit comments

Comments
 (0)