Gunnar Bittersmann: asynchrones JavaScript

Beitrag lesen

@@Gunnar Bittersmann

Sieht jetzt so aus:

lib/language-names.json:

{
	"de": "deutsch",
	"en": "English",
	"es": "español",
	"tlh": "tlhIngan Hol"
}

lib/language-names.de.json:

{
	"de": "deutsch",
	"en": "englisch",
	"es": "spanisch",
	"tlh": "klingonisch"
}

config/available-languages:

["de", "es", "en"]

Markup (HTML):

<ul id="lang-menu">
	<template id="lang-menu-item">
		<li><a></a></li>
	</template>
	<script src="lang-menu.js" async=""></script>
</ul>

lang-menu.js:

var currentLanguage = document.documentElement.lang;

var urls = [
	'config/available-languages.json',
	'lib/language-names.json',
	'lib/language-names.' + currentLanguage + '.json'
];

Promise.all(
	urls.map(
		url => fetch(url).then(response => response.json())
	)
).then(values => {
	
	var [availableLanguages, languageNames, localLanguageNames] = values;
	var template = document.querySelector('#lang-menu-item');

	availableLanguages.forEach(lang => {
		
		if (lang != currentLanguage)
		{
			var clone = template.content.cloneNode(true);
			var liElement = clone.querySelector('li');
			var aElement = liElement.querySelector('a');
			
			aElement.href = '?lang=' + lang;
			aElement.hreflang = lang;
			aElement.lang = lang;
			aElement.textContent = languageNames[lang] || lang;
			liElement.title = localLanguageNames[lang] || '';
			
			template.parentNode.appendChild(clone);
		}
	});
});

Daraus generiertes Markup (DOM), wenn wir uns auf der deutschsprachigen Seite befinden (<html lang="de">:

<ul id="lang-menu">
	<template id="lang-menu-item"></template>
	<script src="lang-menu.js" async=""></script>
	<li title="englisch"><a href="?lang=en" hreflang="en" lang="en">English</a></li>
	<li title="spanisch"><a href="?lang=es" hreflang="es" lang="es">español</a></li>
</ul>

LLAP 🖖

--
“When UX doesn’t consider all users, shouldn’t it be known as ‘Some User Experience’ or... SUX? #a11y” —Billy Gregory