-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (44 loc) · 1.61 KB
/
index.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
function main() {
//---------- i18n
// The locale our app first shows
const defaultLocale = "en";
// The active locale
let locale;
// Gets filled with active locale translations
let translations = {};
// When the page content is ready...
document.addEventListener("DOMContentLoaded", () => {
// Detect the user's locale
const userLocale = navigator.language || navigator.userLanguage;
// Map the detected locale to the appropriate translation file
const supportedLocales = ["en", "is", "sv"];
const newLocale = supportedLocales.includes(userLocale) ? userLocale : defaultLocale;
// Translate the page to the detected or default locale
setLocale(newLocale);
});
// Load translations for the given locale and translate
// the page to this locale
async function setLocale(newLocale) {
if (newLocale === locale) return;
const newTranslations = await fetchTranslationsFor(newLocale);
translations = newTranslations;
locale = newLocale;
// Translate the page content
translatePage();
}
// Fetch translations for the given locale
async function fetchTranslationsFor(locale) {
const response = await fetch(`/lang/${locale}.json`);
return await response.json();
}
// Translate the page content
function translatePage() {
// Implement your translation logic here
// For example, you can iterate over elements with a data-i18n attribute
document.querySelectorAll("[data-i18n-key]").forEach((element) => {
const key = element.getAttribute("data-i18n-key");
element.textContent = translations[key] || key;
});
}
}
main();