Skip to content

Commit 0dda8b5

Browse files
committed
Add lazy loading translations questions
1 parent 6f46418 commit 0dda8b5

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

README.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,7 @@ List of 300 VueJS Interview Questions
219219
|210| [How to implement DateTime localization?](#how-to-implement-date-time-localization)|
220220
|211| [How do you implement Number localization?](#how-do-you-implement-number-localization)|
221221
|212| [How do you perform locale changing](#how-do-you-perform-locale-changin)|
222+
|213| [What is Lazy loading translations?](#what-is-lazy-loading-translations)|
222223

223224
1. ### What is VueJS?
224225
**Vue.js** is an open-source, progressive Javascript framework for building user interfaces that aim to be incrementally adoptable. The core library of VueJS is focused on the `view layer` only, and is easy to pick up and integrate with other libraries or existing projects.
@@ -3853,5 +3854,52 @@ List of 300 VueJS Interview Questions
38533854
}
38543855
</script>
38553856
```
3857+
213. ### What is Lazy loading translations?
3858+
The loading of all translation files at once is unnecessary and it may impact the performance too. It will be easy for lazy loading or asynchronously loading the translation files when you use webpack. i.e, You can dynamically load or import language translations using webpack as below,
3859+
```javascript
3860+
//i18n-setup.js
3861+
import Vue from 'vue'
3862+
import VueI18n from 'vue-i18n'
3863+
import messages from '@/lang/en'
3864+
import axios from 'axios'
3865+
3866+
Vue.use(VueI18n)
3867+
3868+
export const i18n = new VueI18n({
3869+
locale: 'en', // set locale
3870+
fallbackLocale: 'en',
3871+
messages // set locale messages
3872+
})
3873+
3874+
const loadedLanguages = ['en'] // our default language that is preloaded
3875+
3876+
function setI18nLanguage (lang) {
3877+
i18n.locale = lang
3878+
axios.defaults.headers.common['Accept-Language'] = lang
3879+
document.querySelector('html').setAttribute('lang', lang)
3880+
return lang
3881+
}
3882+
3883+
export function loadLanguageAsync (lang) {
3884+
if (i18n.locale !== lang) {
3885+
if (!loadedLanguages.includes(lang)) {
3886+
return import(/* webpackChunkName: "lang-[request]" */ `@/lang/${lang}`).then(msgs => {
3887+
i18n.setLocaleMessage(lang, msgs.default)
3888+
loadedLanguages.push(lang)
3889+
return setI18nLanguage(lang)
3890+
})
3891+
}
3892+
return Promise.resolve(setI18nLanguage(lang))
3893+
}
3894+
return Promise.resolve(lang)
3895+
}
3896+
```
3897+
After that loadLanguageAsync function can be used inside a vue-router beforeEach hook.
3898+
```javascript
3899+
router.beforeEach((to, from, next) => {
3900+
const lang = to.params.lang
3901+
loadLanguageAsync(lang).then(() => next())
3902+
})
3903+
```
38563904
38573905

0 commit comments

Comments
 (0)