element-plus/docs/.vitepress/lang.js
qiang 0c92e8a8d2
docs: only cache the user preferred language pages in the PWA (#7568)
* docs: cache the preferred lang pages in the PWA

* chore: remove index.html in manifest

* fix: no cache the '/' page

* perf: optimize code

* docs: add always refresh from PWA
2022-05-12 22:48:38 +08:00

35 lines
1018 B
JavaScript

;(() => {
const supportedLangs = window.supportedLangs
const cacheKey = 'preferred_lang'
const defaultLang = 'en-US'
// docs supported languages
const langAlias = {
en: 'en-US',
fr: 'fr-FR',
es: 'es-ES',
}
let userPreferredLang = localStorage.getItem(cacheKey) || navigator.language
const language =
langAlias[userPreferredLang] ||
(supportedLangs.includes(userPreferredLang)
? userPreferredLang
: defaultLang)
localStorage.setItem(cacheKey, language)
userPreferredLang = language
if (!location.pathname.startsWith(`/${userPreferredLang}`)) {
const toPath = [`/${userPreferredLang}`]
.concat(location.pathname.split('/').slice(2))
.join('/')
location.pathname =
toPath.endsWith('.html') || toPath.endsWith('/')
? toPath
: toPath.concat('/')
}
if (navigator && navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage({
type: 'LANG',
lang: userPreferredLang,
})
}
})()