You can adapt behaviors and strings per language by deriving locale from the page and scoping logic to specific locales—without relying on undocumented globals or load events.
Pick a detection strategy
Helpers (choose what matches your project)
function getLocale() {// 1) Try <html lang>const lang = document.documentElement.lang;if (lang) return lang;// 2) Try URL prefix like /es/ or /fr-CA/const m = location.pathname.match(/^\/([a-z]{2}(?:-[A-Z]{2})?)\//);if (m) return m[1];// 3) Try explicit data attribute on bodyconst a = document.body.getAttribute('data-locale');if (a) return a;// Fallbackreturn 'en';}const LOCALE = getLocale();Run locale‑specific behavior
// Exit early if this file is only for certain localesconst SUPPORTED = new Set(['en', 'es', 'fr']);if (!SUPPORTED.has(LOCALE)) {// Not a targeted locale; exit safely} else {// Localized logic here}Tiny dictionary pattern
const dict = { en: { cta: 'Add to cart' }, es: { cta: 'Añadir al carrito' }, fr: { cta: 'Ajouter au panier' }};function t(key) {const d = dict[LOCALE] || dict.en;return d[key] || key;}const btn = document.querySelector('[data-i18n="cta"]');if (btn) btn.textContent = t('cta');Right‑to‑left (RTL) basics
const rtlLocales = new Set(['ar', 'he', 'fa', 'ur']);const base = LOCALE.split('-')[0];if (rtlLocales.has(base)) { document.documentElement.dir = 'rtl';}CMS and attributes
Publishing and testing
FAQ