Skip to content

Instantly share code, notes, and snippets.

@FANMixco
Last active August 25, 2022 09:57
Show Gist options
  • Save FANMixco/93549a24c75cf8e9a96dd5b827202f4f to your computer and use it in GitHub Desktop.
Save FANMixco/93549a24c75cf8e9a96dd5b827202f4f to your computer and use it in GitHub Desktop.
A simple solution for translating static websites with JS and a data attribute (data-translation)
These scripts allow people to build static pages with multilingual support without any framework or special libs.
const getScript = url => new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = url;
script.async = true;
script.onerror = reject;
script.onload = script.onreadystatechange = function() {
const loadState = this.readyState;
if (loadState && loadState !== 'loaded' && loadState !== 'complete') return;
script.onload = script.onreadystatechange = null;
resolve();
}
document.head.appendChild(script);
});
const translations = {
"telephone": "Telephone",
"email": "Email",
"contactMe": "Contact me"
};
const translations = {
"telephone": "Teléfono",
"email": "Email",
"contactMe": "Contáctame"
};
<script src="get-script.js"></script>
<script src="translations.js"></script>
<p data-translation="contactMe"></p>
<p data-translation="telephone"></p>
<p data-translation="email"></p>
let lang = 'en';
let nLang = (navigator.languages
? navigator.languages[0]
: (navigator.language || navigator.userLanguage)).split('-')[0];
let supportedLang = ['en', 'es'];
lang = supportedLang.includes(nLang) ? nLang : lang;
getScript(`lang-${lang}.js`)
.then(() => {
document.querySelectorAll('[data-translation]').forEach(item => {
item.innerHTML = translations[`${item.dataset.translation}`];
});
})
.catch((e) => {
console.error(e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment