Skip to content

Commit ffee8f0

Browse files
committed
load locales async and await all
1 parent 2697c90 commit ffee8f0

File tree

2 files changed

+24
-18
lines changed

2 files changed

+24
-18
lines changed

lib/bundles/base.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ window._ = require('lodash');
9898
// signature is almost the same as for PHP functions, but accept extra arguments for string variables
9999
window.i18n = require('gettext.js/lib/gettext').default({domain: 'glpi'});
100100
if (window.loadLocales !== undefined) {
101-
window.loadLocales();
101+
await window.loadLocales();
102102
}
103103

104104
const escape_msgid = function (msgid) {

src/Glpi/Application/View/Extension/FrontEndAssetsExtension.php

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -242,25 +242,31 @@ public function localesJs(): string
242242
$locales_domains[$plugin] = Plugin::getPluginFilesVersion($plugin);
243243
}
244244

245-
foreach ($locales_domains as $locale_domain => $locale_version) {
246-
$locales_path = Html::getPrefixedUrl(
245+
$locales_json = json_encode(array_combine(array_keys($locales_domains), array_map(static function ($domain, $version) {
246+
return Html::getPrefixedUrl(
247247
'/front/locale.php'
248-
. '?domain=' . $locale_domain
249-
. '&v=' . FrontEnd::getVersionCacheKey($locale_version)
248+
. '?domain=' . $domain
249+
. '&v=' . FrontEnd::getVersionCacheKey($version)
250250
);
251-
$script = "
252-
// Fetch locale JSON without jQuery to allow fetching before jQuery is loaded
253-
function loadLocales() {
254-
const xhr = new XMLHttpRequest();
255-
xhr.open('GET', '" . \jsescape($locales_path) . "', false); // synchronous request
256-
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
257-
xhr.send(null);
258-
if (xhr.status === 200) {
259-
i18n.loadJSON(JSON.parse(xhr.responseText), '" . \jsescape($locale_domain) . "');
260-
}
261-
};
262-
";
263-
}
251+
}, array_keys($locales_domains), $locales_domains)));
252+
253+
$script = <<<JS
254+
// Fetch locale JSON without jQuery to allow fetching before jQuery is loaded
255+
async function loadLocales() {
256+
const locales = $locales_json;
257+
const promises = [];
258+
for (const [domain, url] of Object.entries(locales)) {
259+
promises.push(window.fetch(url).then(response => {
260+
if (response.ok) {
261+
return response.json().then(data => {
262+
i18n.loadJSON(data, domain);
263+
});
264+
}
265+
}));
266+
}
267+
await Promise.all(promises);
268+
}
269+
JS;
264270

265271
return Html::scriptBlock($script);
266272
}

0 commit comments

Comments
 (0)