What's the current best practice of handling i18n in JavaScript?
I've heard some suggestions involving outputting all the i18n strings using PHP/Rails/etc. into a formatted JavaScript file of thousands of vars, but that simply sounds too rough a solution; moreover, there needs to be a way to detect which i18n strings are actually needed for the JS files that's gonna be loaded on a given page, but I got no idea how to implement this right now.
Some other suggestions I've heard involving setting up some kind of API between backend and frontend, using well-formatted JSON as the carrier of i18n strings, but that still doesn't solve the problem with redundant strings I might not need.
What's some of the best practices regarding i18n in JavaScript currently, that - if possible - also have a solution for detecting and sending only those strings that are actually needed on a given page?
The 'best practice' really depends on how you build you application. Two examples:
Either way, you'll want to reduce the amount of strings sent to the client to a bare minimum. While there are a lot of approaches, my favorite is to use pre-compiled templates (I like Mustache using Twitter's Hogan.js) with i18n extensions that don't only return a function to generate the HTML, but also a list of all translatable strings.
What you definitely don't want to do is to build a function that checks whether you already have a translation and if you don't then ask the server. This will make everything very slow and you don't want that. Either pre-load all translations, or don't translate those parts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With