Skip to content

Instantly share code, notes, and snippets.

@zbraniecki
Last active August 29, 2015 14:24
Show Gist options
  • Save zbraniecki/09ede6bdb7bd125e1626 to your computer and use it in GitHub Desktop.
Save zbraniecki/09ede6bdb7bd125e1626 to your computer and use it in GitHub Desktop.
let promises = [];
let l10nResLinks = document.head.querySelectorAll('link[rel=localization]');
for (link of l10nResLinks) {
promises.push(link.ready);
};
Promise.all(promises).then(function (resources) {
return Promise.all(resources.map(function(response) {
if (!response.ok) {
console.log('error fetching ' + response.url);
return;
}
if (response.url.endsWith('.json')) {
return response.json();
} else {
return response.text();
}
}).filter(n => n !== undefined));
}).then(function(responses) {
console.log(responses);
});
(function() {
const observerConfig = {
attributes: false,
characterData: false,
childList: true,
subtree: false,
};
var observer = new MutationObserver(onMutations);
observer.observe(document.head, observerConfig);
let l10nMeta = new Map();
let localeChain = new Set();
let currentLocale;
document.head.l10nResourceLinks = new Set();
function onMutations(mutations) {
for (let mutation of mutations) {
for (let addedNode of mutation.addedNodes) {
if (addedNode.nodeType === Node.ELEMENT_NODE) {
onAddedHeadElement(addedNode);
}
}
}
}
function onAddedHeadElement(element) {
if (element.nodeName === 'LINK' &&
element.getAttribute('rel') === 'localization') {
document.head.l10nResourceLinks.add(element);
if (currentLocale) {
initLinkLoading(element);
}
} else if (element.nodeName === 'META') {
let name = element.getAttribute('name');
if (name === 'defaultLanguage' || name === 'availableLanguages') {
l10nMeta.set(name, element.getAttribute('content'));
if (l10nMeta.size === 2) {
startL10n();
}
}
}
}
function negotiateLocales() {
localeChain.add('en-US');
localeChain.add('fr');
return Promise.resolve();
}
function initResourceLoading() {
currentLocale = [...localeChain][0];
for (link of document.head.l10nResourceLinks) {
initLinkLoading(link);
}
}
function initLinkLoading(link) {
let href = link.getAttribute('href');
href = href.replace('{locale}', currentLocale);
link.ready = fetch(href).then(function(response) {
return response;
});
}
function startL10n() {
negotiateLocales().then(initResourceLoading);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment