Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading translation files on demand

A standard approach for translation using i18next usually involves loading all the translation files at once, as soon as the web app is loaded.

i.e

i18n
    .use(XHR)
    .use(LanguageDetector)
    .init({
        fallbackLng: 'en',
        debug: false,

        keySeparator: false,

        interpolation: {
            escapeValue: false,
            formatSeparator: ','
        },

        resources: {
            en: {
                translations: en
            },
            ru: {
                translations: ru
            },
            es: {
                translations: es
            }
        },

        ns: ['translations'],
        defaultNS: 'translations',

        react: {
            wait: true
        }
});

I find this approach quite inefficient and would like to request translation files from the server as needed (i.e when the client switches the language). Unfortunately, I didn't find any reference to that in the official documentation but there certainly should be a way of accomplishing this.

Schema of what I want to achieve:

1) Web app loads along with only default translation file (e.g english.json)

2) If the user switches the language – let's say to Spanish – spanish.json is being loaded from the server and the whole translation is adjusted.

like image 330
Kamran Poladov Avatar asked Dec 11 '19 20:12

Kamran Poladov


People also ask

What is i18n and i18next?

i18n is the abbreviation for internationalization. i18next is a JavaScript framework enabling internationalization.

What is namespace in i18next?

Namespaces are a feature in i18next internationalization framework which allows you to separate translations that get loaded into multiple files. While in a smaller project it might be reasonable to just put everything in one file you might get at a point where you want to break translations into multiple files.


1 Answers

From the API documentation for the .init() method's configuration options:

partialBundledLanguages — allows some resources to be set on initialization while others can be loaded using a backend connector

So, setting the option to true will achieve what you're aiming for.

like image 126
Rafael Sofi-zada Avatar answered Oct 23 '22 06:10

Rafael Sofi-zada