how to create a language file for text in javascript files?

javascript, jquery, multilingual

Solution

Create an object literal:

var messages = {
    welcome: "Welcome",
    goodbye: "Goodbye",
    error: "Something bad happend. Sowwy!"
};

Which you can then reference, like so:

if (error) alert(messages.error);

This works great if you want to implement multiple languages. What I usually do is include a server-side file which renders out a "messages" object according to whatever language is selected in the configuration of the app or according to the UI-culture (in the case of ASP.NET).

Here's how you would use it, in-line:

<head>
    <!-- messages.aspx renders out the object literal -->
    <script type="text/javascript" src="messages.aspx"></script>

    <script type="text/javascript">

        /* when messages.aspx is included it provides you with an object literal
           as a global variable. The example below would alert "Something bad
           happend. Sowwy!" */

        if (error) alert(messages.error);

    </script>
</head>

The neat thing about using an object literal, is that the code is more verbose. Instead of using an array, like this: `alert(messages[0])` you do this: `alert(messages.error)` which is a bit more explanatory.

On a side-note: all your messages are defined in one object, instead of being defined by a bunch of variables, thereby avoiding polluting the global namespace. In JavaScript you can modify objects at run-time. So if you wanted to add more messages to the object, later on in your code, you'd just do this:

messages.newMessageAddedLaterOnInTheCode = "This is a new message";

Problem

My web application uses allot of javascript, and in the javascript I have messages that I report back to the user. What is the best way to extract the text from my javascript and store it externally in another .js language file, and how would I reference it in my js code going forward? Any best practices for this?

Original source