Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i18n for JavaScript - The Best Practice?

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?

like image 592
gsklee Avatar asked Sep 03 '26 14:09

gsklee


1 Answers

The 'best practice' really depends on how you build you application. Two examples:

  • Single page app. Of course you'd want to just load all of the needed strings for you entire application in one go, as constantly fetching new strings would be a waste of time and resources.
  • Page with some JS-based content. If you keep reloading the JS, you probably want to reduce the amount of strings as much as possible, and maybe even integrate the entire i18n dict in your HTML to avoid a AJAX call.

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.

like image 155
Tom van der Woerdt Avatar answered Sep 06 '26 03:09

Tom van der Woerdt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!