I got a json file for some translations. I would like to use this file in a JS file to translate some strings. But i do not get a good solution to load this file and data.
What i got so far is in my HTML File:
<script type='application/json' src='lang/translations.json'></script>
<script src="Javascript/translator.js" charset="UTF-8"></script>
JSON File:
{
"language": {
"en": {
"closure": "Closure",
"documents": "Documents",
"overview": "Overview"
},
"de": {
"closure": "Abschluss",
"documents": "Dokumente",
"overview": "Übersicht"
}
}
}
And my JS file:
let docLanguage = document.documentElement.lang;
let browserLanguage = navigator.language.substr(0, 2);
let lang = docLanguage ? docLanguage : browserLanguage;
let texts;
const Http = new XMLHttpRequest();
const url = "lang/" + lang + ".json";
Http.open("GET", url, false);
Http.send();
Http.onreadystatechange = function () {
texts = JSON.parse(Http.responseText);
return texts;
}
let getJson = jQuery.getJSON('lang/' + lang + '.json', {format: "json", async: false})
.done(function (data) {
// texts = data;
return data;
}).fail(function () {
console.log('empty');
});
class translator {
constructor(lang) {
this.lang = lang;
this.translations = texts;
}
_(keyName) {
// return texts.get(keyName);
// todo get by keyName
}
transHtml(attribute = 'data-lang') {
let htmlElements = document.querySelectorAll('[' + attribute + ']');
for (let htmlElement of htmlElements) {
let keyName = htmlElement.getAttribute(attribute);
htmlElement.textContent = this._(keyName);
}
}
}
var translate = new translator(lang);
But the Problem is, that the translations file is read to late and in the constructor i can not use this parts, or am i doing something wrong?
So what is the best way to load and read a json file which is stored local.
I do not want a server or anything else, only pure Javascript which can run on all modern Browsers. Because this is an Export for users and they should be able to just watch this page without the need of installing anything or the need of a internet connection