Today, I created a passive localization JavaScript library named l10n.js. l10n.js is a JavaScript library that enables passive localization through native JavaScript methods, gracefully degrading if the library is not present. You can make Ajax applications, JavaScript libraries, etc. that can be localized but not require l10n.js to function. There is already a placeholder method for all API calls as specified in the ECMAScript specification and is present in all JavaScript engines, so when l10n.js isn’t present, your application works fine.
Demo
You can try out the online demo to see l10n.js in action. Currently, only the languages mentioned in the readme are supported, but more will eventually be added.
Usage
API
API documentation can be found in the readme. All API calls gracefully degrade, so calling them even without l10n.js loaded causes no problems.
Localizing strings
Calling toLocaleString()
on every localizable string can create a lot of extra typing and bloat for sending your JavaScript down the wire. I recommend using the following helper function to localize strings. The reason I don’t define this in l10n.js is to not introduce any new globals, which keeps l10n.js a one of the JavaScript libraries least-prone to conflicts with other libraries.
var l = function (string) { return string.toLocaleString(); }; |
With this helper function, you can start writing l("Your localizable string")
instead of "Your localizable string".toLocaleString()
. I chosel
instead of _
(an underscore), because it’s easier to spot so you can quickly skim your code to see which strings are localizable.
Variable replacement
If you don’t mind requiring l10n.js for your JavaScript application or library to function, I suggest using short variable strings instead of default strings. It saves bandwidth by decreasing the size of localization files, and it enables you to write nice, short code as such in the following.
document.title = l("%title.search")
- Example results:
"Seach - Acme, Inc."
- Example results:
confirm(l("%confirm.deleteAccount"))
- Example results:
"Are you sure you want to delete your account?"
- Example results:
link.href = "http://www.google" + l("%locale.tld")
- Example results:
"http://www.google.co.uk"
- Example results:
Often, string concatenation is used instead of replacement in JavaScript. With l10n.js, to make localization easier, you may have to use replacements instead. You might want to use a JavaScript library that implements something similar to C++’s sprintf()
. A nice JavaScript implementation I’d recommend is php.js’s sprintf()
.
When localizations are downloaded
If you are using single localization URLs (<link rel="localization" hreflang="..." href="..." type="application/vnd.oftn.l10n+json"/>
), they will only be downloaded when needed. If you are using multiple localizations in one (<link rel="localizations" href="..." type="application/vnd.oftn.l10n+json"/>
), then the file will be downloaded right away, but externally linked localizations in the localization file will not be. If you provide an interface for your users to change locales, any non-loaded localization files will be loaded when necessary.
Including localizations with link elements
Multiple localizations can be included with one localization JSON file, with all of the top properties being language codes. Instead of putting all of the localized strings directly in the file, you may want to assign a specifc localization JSON URL to each locale, as to save bandwidth by only downloading locales the user needs.
The following is an example localization file for <link rel="localizations" href="path/to/localizations.json" type="application/vnd.oftn.l10n+json"/>
.
{ "en-US": { "What is your favourite colour?": "What is your favorite color?" }, "fr": "path/to/french-localization.json" } |
Using localization files is the same as calling String.toLocaleString()
with the JSON localizations object as the first parameter.
You can also include single localizations by specifying the standard HTML5 hreflang
link element attribute and using a rel of localization
instead of localizations
with an ‘s’, as shown in the following.
<link rel="localization" hreflang="en-US" href="american-english.json" type="application/vnd.oftn.l10n+json"/> |
The JSON file for the localization might look like the following.
{ "What is your favourite colour?": "What is your favorite color?" } |
[…] been doing some great work that we will be featuring here on Ajaxian. First up we have his recent l10n.js, which is a JavaScript library that enables localization through the native JavaScript method […]
Do you know whether there are any current standardization efforts (perhaps relating to HTML5 or ARIA) in the area of localization? I can't find much information on the various dev wikis for the standards bodies.
@Andy,
There's a proposal on the CommonJS wiki:http://wiki.commonjs.org/wiki/I18n
Don't think there's anything going on with it currently.
[…] via Ajaxian, descubro l10n.js, una librería javascript que permite realizar esta idiomatización desde el cliente, usando una estructura JSON donde alojas las frases en los diferentes […]
Hi, I've just created a symfony plugin based on your work (http://www.symfony-project.org/plugins/ncJavascriptLocalizationPlugin). Great job!
Nice work on the plugin!
[…] 本日紹介する「l10n.js」というライブラリを使用すると言語に依存するメッセージを多言語対応させる事が可能です。 […]
[…] que al llegar al usuario las frases ya están en el idioma seleccionado. Hoy via Ajaxian, descubro l10n.js, una librería javascript que permite realizar esta idiomatización desde el cliente, usando una estructura JSON donde alojas las frases en los diferentes […]
[…] Url: http://eligrey.com/blog/post/localization-in-javascript […]
[…] a comment » Eli Grey released week ago a great library for localizing JavaScript code. Today, we want to support this great library by providing support […]
Do you know whether there are any current standardization efforts (perhaps relating to HTML5 or ARIA) in the area of localization? I can't find much information on the various dev wikis for the standards bodies.
You may want to look into W3C I18n.
Hi, great stuff, but it would be really good if we could override the U-A’s locale (for test purposes, if not staged release of languages, or maybe even locale mapping – US & AUS both mapped to the UK resources – at least to start with).
As an example, we’re localising for several locales (right now) but we only want ‘en-GB’ to kick-in for the moment (- until, potentially one-by-one, we are finally ready/in agreement to support an/the additional language/s).
Set
String.locale
to manually set the locale. For an example of manually settingString.locale
refer to the source code of the demo, where it is used to allow for locale-specific permalinks.[…] Passive Localization in JavaScript — Eli Grey (tags: javascript i18n library howto) […]
[…] searching for while I found this post about Passive localization in JavaScript. Of course, I would prefer an officially standardized approach for the localization, but anyway, […]
[…] ich eine Weile gesucht habe, fand ich diesen Post über passive Lokalisierung in JavaScript. Natürlich wäre mir ein offiziell standardisierter Ansatz zur Lokalisierung lieber gewesen, […]
Great library, and very easy to use 🙂
Hi, thanks for the library, I am using it on a microcontroller HTML UI, and wanted to keep it in JS (no JQuery, to keep size down).
For now I use: document.write(l(“key”)); in the HTML. Quick and dirty.
Is there a reason for starting the key strings with %?
A different approach, when using a framework, is shown here:
http://blog.katworksgames.com/2012/12/23/translated-strings-and-foreign-language-support/
If you’re interested in alternative localization solutions, have a look at https://poeditor.com/
It’s integrated with GitHub.
hello, great article and work but I would like to know if your library support automatically date,currency,number… formatting and can I use the library in phonegap project(can it support phonegap supported platforms android,ios,blackberry,windows phone 7 and 8,…..)
Hi, Eli,
Thank you for your great work on the internationalization. I’ve recently started working on web development. Your library works great, just one small problem. If I use <i> tags with font-awesome along with the <a> tag, the text does not get replaced. For example,
<a><i></i>some_text_to_localize</a>
does not replace “some_text_to_localize” with the correct string.
the same string without the <i> tags, get replaced without problem.
could you please explain how to modify the script so as to be able to replace the text with icons? it is important as nowadays font awesome is really common.
Thanks,
K.