Quantcast
Channel: Don't call me DOM » Web development
Viewing all articles
Browse latest Browse all 15

Determining the user’s language in JavaScript

$
0
0

When one wants to use JavaScript to add language-specific content to a page (for instance, for localization), the only cross-browser property available is navigator.language, which unfortunately represents the browser’s language, not the user’s preferred language — that browsers often make configurable.

This makes navigator.language pretty much inappropriate as a base for a solid localization effort.

While the browser sends the preferred language with each request to any server through the Accept-Language HTTP header, the client-side JavaScript engine doesn’t have access to the value of that header, and so cannot even try to parse it to determine the user’s preferred language.

A work-around I have found is to rely on good ole HTTP-based language negotiation:

  • you store your localized content in external JSON files, one per language, set up to be language-negotiated — typically, using Apache multiviews, you would have file.js.en and file.js.fr in the same directory, say http://example.org/lang/;
  • you then load that localized content through XMLHTTPRequest, accessing the “generic” URI, in our example http://example.org/lang/file.js;
  • since the browser will send the proper Accept-Language HTTP header to the server when doing the XMLHTTPRequest, and since the server will send the JSON file that matches best the user’s stated preferences, your script will then be getting the properly localized JSON file.

This costs an additional HTTP request, but that cost can be reduced by setting a long Expires header for the JSON files, or entirely removed by not separating the localized content out of the script, and instead serve the script itself through language negotiation (to the cost of maintaining the script in N versions for N languages.


Viewing all articles
Browse latest Browse all 15

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>