• Stars
    star
    392
  • Rank 105,817 (Top 3 %)
  • Language
    JavaScript
  • License
    Other
  • Created almost 14 years ago
  • Updated about 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Passive localization JavaScript library

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

This repository includes a simple demo that you can try out on your webserver.

If you know a language that isn't currently supported in the demo, I encourage you to contribute a localization by sending me your own localizations, either through GitHub or directly. The following strings would need to be localized:

  • %title to {Locale} - l10n.js demo in the locale.
  • %info to You are viewing a {locale} localization of this page. in the locale.
  • Optionally, %locale.dir to rtl if the locale uses right-to-left directionality.

Supported Browsers

  • Internet Explorer 5+
  • Firefox 2+
  • Opera 9+
  • Google Chrome 1+
  • Safari 4+

Getting Started

  1. Download l10n.js.
  2. Localize strings used in your JavaScript application. See the demo localizations file for an example localizations file. You can also specify external localizations in your main localizations file by assigning a URL string to a language code, such as "en-us": "localizations/en-us.json".
  3. Include the appropriate link elements, as described in the usage section, anywhere in your document. I recommend putting it in the document's <head>.
  4. Place <script type="text/javascript" src="path/to/l10n.js"></script> anywhere after the <link> tag.
  5. Call toLocaleString() on any strings you wish to localize.

Usage

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 chose l 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: "Search - Acme, Inc."
  • confirm(l("%confirm.deleteAccount"))
    • Example results: "Are you sure you want to delete your account?"
  • link.href = "http://www.google." + l("%locale.tld")
    • Example results: "http://www.google.co.uk"

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() witht 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?"
}

API

Strong and emphasized text has titles (which can be viewed by hovering your cursor over them) containing their type if they are not functions or return type if they are.

Methods

String.toLocaleString([localizations])
If localizations is an object, it is added to the localizations.
If localizations is a string, it is requested as JSON and then added to the localizations.
If localizations is false, then all localizations are reset.
If localizations is an object, and a locale is false, then all localizations for that locale are reset.

The string representation of the String contructor is returned, to maintain backwards compatibility with any code using this method to actually get it.

<h4>Examples</h4>
<ul>
  <li>
    Loading a localizations JSON file:
    <pre><code>String.toLocaleString(<strong title="String">"path/to/localizations.json"</strong>)</code></pre>
  </li>
  <li>
    Defining localizations directly:
    <p>
      The nearest locale to the user's locale that has the string being localized is
      used in localization.
    </p>
    <pre><code>String.toLocaleString({
"es": { // Spanish
    "Hello, world!": "¡Hola, mundo!"
    // more localizations...
},
"en-US": { // American English
    "Hello, world!": "Hello, America!" // Locale-specific message
    // more localizations...
},
"en-GB": false, // resetting British English localizations
// Specifying external localization JSON for Japanese:
// The URL isn't requested unless the user's locale is Japanese
"ja": "localizations/ja.json"

})

  • Resetting all localizations:
    String.toLocaleString(false)
  • aString.toLocaleString()
    Returns the localized version of aString in the user's locale, if available. Otherwise, it returns the same string.

    Fields

    String.locale
    A configurable string which represents the language code of the locale to use for localization. It defaults to the user's own locale.
    String.defaultLocale
    A configurable string which represents the language code of the default locale to use for localization if no localizations are available in the user's locale. By default this is not configured, and may be ignored if you are using l10n.js for passive-only localizations.

    Default locale

    The "" (empty string) locale is the default locale, where you can specify default or fallback strings.

    More Repositories

    1

    FileSaver.js

    An HTML5 saveAs() FileSaver implementation
    JavaScript
    20,738
    star
    2

    Blob.js

    An HTML5 Blob implementation
    JavaScript
    1,141
    star
    3

    classList.js

    Cross-browser element.classList
    JavaScript
    1,105
    star
    4

    canvas-toBlob.js

    A canvas.toBlob() implementation
    JavaScript
    657
    star
    5

    jsandbox

    A JavaScript sandboxing library that uses web worker threads
    JavaScript
    190
    star
    6

    color.js

    Color management JavaScript libary
    JavaScript
    157
    star
    7

    async-document-write

    An asynchronous document.write implementation
    JavaScript
    65
    star
    8

    pmxdr

    Cross-domain XHR using postMessage
    JavaScript
    63
    star
    9

    voice-search

    Chrome extension for searching by speaking.
    JavaScript
    48
    star
    10

    async.js

    async/await before promises. async.js facilitates asynchronous actions ('promises') with synchronous-style syntax
    JavaScript
    41
    star
    11

    timer.js

    High-precision JavaScript timer
    JavaScript
    37
    star
    12

    Xccessors

    Xccessors (cross-browser accessors) is a JavaScript shim that implements the legacy or standard methods for defining and looking up accessors (getters and setters) of objects.
    JavaScript
    36
    star
    13

    RetargetMouseScroll

    A JavaScript library for retargetting mouse scroll events.
    HTML
    35
    star
    14

    libxdr

    A library that implements a cross-browser XDR constructor
    JavaScript
    27
    star
    15

    hotlink.js

    Hide image referrers
    JavaScript
    26
    star
    16

    jData-host

    jData host JavaScript library.
    JavaScript
    18
    star
    17

    mumbl

    A JavaScript library that abstracts audio-playing functionality of HTML5, Songbird, and SoundManager 2 for use in music playlists
    JavaScript
    17
    star
    18

    tinylog

    A minimalistic logging platform
    JavaScript
    17
    star
    19

    reddit-bots

    A collection of various reddit bots.
    Python
    17
    star
    20

    emoji-favicon-toolkit

    Emoji Favicon Toolkit - Set your favicon to emoji using canvas & cache as /favicon.ico with service workers
    TypeScript
    15
    star
    21

    e4x.js

    Implementation of all of the optional features in the ECMA-357 specification.
    JavaScript
    13
    star
    22

    subscribe.js

    An easy-to-use and highly extensible client-side notification-based feed reader Service Worker (coming soon!)
    JavaScript
    11
    star
    23

    mutaprophylaxis

    Methods for preventing unauthorized DOM mutations
    JavaScript
    10
    star
    24

    code.eligrey.com-archive

    Archive of code.eligrey.com
    JavaScript
    8
    star
    25

    attrs

    JavaScript 1.6+ library for setting DOM element attributes
    JavaScript
    7
    star
    26

    chrome-enhanced-font-smoothing

    Chrome extension that that improves font smoothing on Windows
    CSS
    6
    star
    27

    CiteDrag

    CiteDrag automatically cites data dragged from one website to a normal text input (ie. input type="text", textarea) or rich text input field (ie. Microsoft Word, contenteditable HTML elements, your blogging platform, etc.)
    JavaScript
    5
    star
    28

    BlobBuilder.js

    Moved to https://github.com/eligrey/Blob.js
    4
    star
    29

    js-iterators

    A collection of iterator and generator-related JavaScript scripts.
    JavaScript
    4
    star
    30

    http-index-format-automator

    Generates application/http-index-format for directory listings
    PHP
    3
    star
    31

    mixest-downloader

    Adds download functionality to mixest.com.
    JavaScript
    3
    star
    32

    jil

    jData Interface Library (client JavaScript library)
    JavaScript
    3
    star
    33

    myrandom.js

    reddit's paywalled myrandom button, for everyone
    JavaScript
    2
    star
    34

    e4x-array-methods.js

    A JavaScript library that implements array methods for E4X XML. Intended for making XML easier to use with server-side JavaScript.
    JavaScript
    2
    star
    35

    docswap

    DOM document replacement tools
    TypeScript
    1
    star
    36

    clipvertise

    Use the clipboard for ads or something
    1
    star
    37

    speculative-request-control

    Speculative Request Control explainer
    Bikeshed
    1
    star