Skip to content

Commit caf275e

Browse files
[refactor] Simplify loadJSON function in translator.js
1 parent 85b4ece commit caf275e

File tree

2 files changed

+12
-20
lines changed

2 files changed

+12
-20
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ planned for 2025-07-01
3131
- Switch Stylelint config to flat format and simplify Stylelint scripts
3232
- [workflow] Replace Node.js version v23 with v24 (#3770)
3333
- [refactor] Replace deprecated constants `fs.F_OK` and `fs.R_OK` (#3789)
34+
- [refactor] Simplify the `loadJSON` function in `translator.js` by replacing `XMLHttpRequest` with `fetch` (#3792)
3435

3536
### Fixed
3637

js/translator.js

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,30 +3,21 @@
33
const Translator = (function () {
44

55
/**
6-
* Load a JSON file via XHR.
6+
* Load a JSON file using fetch.
77
* @param {string} file Path of the file we want to load.
88
* @returns {Promise<object>} the translations in the specified file
99
*/
1010
async function loadJSON (file) {
11-
const xhr = new XMLHttpRequest();
12-
return new Promise(function (resolve) {
13-
xhr.overrideMimeType("application/json");
14-
xhr.open("GET", file, true);
15-
xhr.onreadystatechange = function () {
16-
if (xhr.readyState === 4 && xhr.status === 200) {
17-
// needs error handler try/catch at least
18-
let fileInfo = null;
19-
try {
20-
fileInfo = JSON.parse(xhr.responseText);
21-
} catch (exception) {
22-
// nothing here, but don't die
23-
Log.error(` loading json file =${file} failed`);
24-
}
25-
resolve(fileInfo);
26-
}
27-
};
28-
xhr.send(null);
29-
});
11+
try {
12+
const response = await fetch(file);
13+
if (!response.ok) {
14+
throw new Error(`HTTP error! status: ${response.status}`);
15+
}
16+
return await response.json();
17+
} catch (error) {
18+
Log.error(`Loading json file ${file} failed: ${error.message}`);
19+
return null;
20+
}
3021
}
3122

3223
return {

0 commit comments

Comments
 (0)