Skip to content

Commit e42d989

Browse files
committed
Avoid initializing the library several times
1 parent 7e2ff48 commit e42d989

File tree

1 file changed

+22
-16
lines changed

1 file changed

+22
-16
lines changed

src/routes/[...lang]/__layout.svelte

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,36 @@
11
<script context="module" lang="ts">
22
import { registerAll, availableLocales } from '$locales';
3-
import { t, waitLocale, init } from 'svelte-intl-precompile';
3+
import { waitLocale, init, locale } from 'svelte-intl-precompile';
44
import { goto } from '$app/navigation';
55
import { page } from '$app/stores';
66
registerAll();
77
let defaultLang = 'en';
8-
let localeRegex = new RegExp(`^/(${availableLocales.join('|')})(/|$)`)
8+
let localeRegex = new RegExp(`^/(${availableLocales.join('|')})(/|$)`);
9+
let initialized = false;
10+
function extractLanguageFromPath(path) {
11+
return (localeRegex.exec(path) || [null, defaultLang])[1];
12+
}
913
export async function load({ url: { pathname } }) {
10-
const lang = (localeRegex.exec(pathname) || [null, defaultLang])[1];
11-
init({
12-
initialLocale: lang,
13-
fallbackLocale: defaultLang
14-
});
15-
await waitLocale()
16-
return {
17-
props: {
18-
lang
19-
}
20-
};
14+
if (!initialized) {
15+
const lang = extractLanguageFromPath(pathname);
16+
init({
17+
initialLocale: lang,
18+
fallbackLocale: defaultLang
19+
});
20+
initialized = true;
21+
await waitLocale()
22+
}
23+
return {};
2124
}
2225
</script>
2326
<script lang="ts">
24-
export let lang: string
25-
2627
const flags = import.meta.globEager('../../lib/flags/*.svg')
27-
28+
$: lang = extractLanguageFromPath($page.url.pathname);
29+
$: {
30+
if ($locale !== lang) {
31+
$locale = lang;
32+
}
33+
}
2834
function flagFor(lang) {
2935
return flags[`../../lib/flags/${lang}.svg`].default
3036
}

0 commit comments

Comments
 (0)