2016年10月17日月曜日

How does internationalization work in JavaScript?

Localisation support in legacy browsers is poor. Originally, this was due to phrases in the ECMAScript language spec that look like this:

Number.prototype.toLocaleString()
Produces a string value that represents the value of the Number formatted according to the conventions of the host environment's current locale. This function is implementation-dependent, and it is permissible, but not encouraged, for it to return the same thing as toString.

Every localisation method defined in the spec is defined as "implementation-dependent", which results in a lot of inconsistencies. In this instance, Chrome Opera and Safari would return the same thing as .toString(). Firefox and IE will return locale formatted strings, and IE even includes a thousands separator (perfect for currency strings). Chrome was recently updated to return a thousands-separated string, though with no fixed decimal.

For modern environments, the ECMAScript Internationalization API spec, a new standard that complements the ECMAScript Language spec, provides much better support for string comparison, number formatting, and date and time formatting; it also fixes the corresponding functions in the Language Spec. An introduction can be found here. Implementations are available in:

·         Chrome 24

·         Firefox 29

·         Internet Explorer 11

·         Opera 15

There is also a compatibility implementation, Intl.js, which will provide the API in environments where it doesn't already exist.

Determining the user's preferred language remains a problem, since there's no specification for obtaining the current language. Each browser implements a method to obtain a language string, but this could be based on the user's operating system language or just the language of the browser:

// navigator.userLanguage for IE, navigator.language for others
var lang = navigator.language || navigator.userLanguage;

A good workaround for this is to dump the Accept-Language header from the server to the client. If formatted as a JavaScript, it can be passed to the Internationalization API constructors, which will automatically pick the best (or first-supported) locale.

In short, you have to put in a lot of the work yourself, or use a framework/library, because you cannot rely on the browser to do it for you.

Various libraries and plugins for localisation:

·         Mantained by an open community (no order):

·         Intl.js - a compatibility implementation of the Internationalisation API

·         i18next (home) for i18n (incl. jquery plugin, translation ui,...)

·         moment.js (home) for dates

·         numbro.js (home) (was numeral.js (home)) for numbers and currency

·         l10n.js (home)

·         L10ns (home) tool for i18n workflow and complex string formatting

·         jQuery Localisation (plugin) (home)

·         YUI Internationalization support

·         jquery.i18Now for dates

·         browser-i18n with support to pluralization

·         counterpart is inspired by Ruby's famous I18n gem

·         jQuery Globalize jQuery's own i18n library

·         Others:

·         jQuery Globalization (plugin)

·         requirejs-i18n Define an I18N Bundle with RequireJS.

 

HTML Elements and Attributes

 

Element/Attribute(s)

Description

Version

a

For creating links and anchors

 

href

For specifying the URL of a page or the name of an anchor that a link goes to

hreflang

For specifying the language of the linked resource

5

media

For describing the media for which the target document was defined

5

rel

For identifying the nature of the link

target

For specifying the window or iframe where a link should open

*

type

For noting a resource's MIME type

abbr

For explaining the meaning of abbreviations and acronyms

*

address

For identifying contact information for the nearest article or body element ancestor

area

For specifying the coordinates of image maps

accesskey

For adding a keyboard shortcut to a particular region of the map

alt

For giving information about an area

coords

For giving the coordinates of an area in an image map

href

For specifying the destination URL of a link in an area of an image map

hreflang

For specifying the language of the linked resource

5

media

For describing the media for which the target document was defined

5

rel

For identifying the kind of link

shape

For specifying the shape of an area in an image map

target

For specifying the window or iframe where a link should open

*

article

For identifying a self-contained composition in a page that is in principle independently distributable or reusable

5

aside

For identifying a section of a page that consists of content that is tangentially related to the content around it

5

audio

For embedding sound or audio in a page

5

autoplay

For telling the browser to start playing the audio file as soon as it can

5

controls

For telling the browser to provide controls for the audio element

5

crossorigin

For setting cross-origin request credentials

5

loop

For telling the audio file to start over without interruption upon reaching its end

5

mediagroup

For associating multiple media files together

5

muted

For controlling the default state of audio output

5

preload

For specifying whether the browser can begin downloading the audio file before the visitor starts playing it

5

src

For identifying the URL of the audio file to play

5

b

For identifying a span of text to which attention is being drawn for utilitarian purposes, without conveying any extra importance and with no implication of an alternate voice or mood

*

base

For specifying the base URL of the page

href

For specifying the URL to be used to generate relative URLs

target

For specifying the default target for the links on the page

*

bdi

For identifying a span of text that is to be isolated from its surroundings for the purposes of bidirectional text formatting

5

dir

For specifying text direction

5

bdo

For explicitly formatting the text direction of its content

dir

For specifying text direction

blockquote

For identifying a section quoted from another source

cite

For giving the URL of the source

body

For enclosing the main content area of a page

br

For creating a line break

button

For creating buttons

autofocus

For specifying that the button is to be focused as soon as the page is loaded

5

disabled

For indicating that the element is not available in the current state

form

For associating the element with a form that it is not a part of

5

formaction

For overriding the form's action attribute

5

formenctype

For overriding the form's enctype attribute

5

formmethod

For overriding the form's method attribute

5

formnovalidate

For overriding the form's novalidate attribute

5

formtarget

For overriding the form's target attribute

5

name

For identifying the data sent with a button, or for identifying the button itself (perhaps for a JavaScript function)

type

For using the button in a form element

value

For specifying the data that should be submitted when the button is clicked

canvas

To provide scripts with a resolution-dependent bitmap canvas for rendering graphics on the fly

5

width, height

For specifying the size of the canvas

5

caption

For creating a caption for a table

cite

For marking text as a citation

code

For marking text as computer code

col

For joining columns in a table into a non-structural group

span

For specifying the number of columns in a column group

colgroup

For joining columns in a table into a structural column group

span

For specifying the number of columns in a column group

command

For representing a command the user can invoke, such as defining a keyboard command

5

checked

For indicating the checked state of the command (if the command type is "checkbox" or "radio")

5

disabled

For indicating that the command is not available in the current state

5

icon

For providing an image that represents the command

5

label

For showing the name of the command to the user

5

radiogroup

For identifying the radio buttons that will be toggled when the command is toggled (if the command type is "radio")

5

type

For indicating the type of command

5

datalist

To contain a group of option elements that represent a predefined set of options for another form control

5

dd

For marking a definition in a list

details

For creating a disclosure widget from which the visitor can obtain additional information or controls

5

open

For specifying whether the element is open or closed by default

5

del

To mark deleted text

cite

For referencing a URL that explains the change

datetime

For specifying the time and date of the change

dfn

For specifying the defining instance of a term

title

For providing the definition of the term

div

For dividing a page into block-level sections

dl

For creating a definition list

dt

For marking a term to be defined in a list

em

To mark text that has stress emphasis

*

embed

For adding multimedia

*

src

For specifying the URL of a multimedia file

type

For identifying the MIME type of the multimedia file

width, height

For specifying the size of the embedded multimedia player

fieldset

For grouping a set of form elements together

disabled

For disabling all form controls within the fieldset

5

form

For associating the element with a form that it is not a part of

5

name

For providing the fieldset with a name for use later

5

figcaption

For identifying a caption or legend for the contents of its parent figure element

5

figure

For identifying content that is referenced within the main flow of the document but that could be moved elsewhere without affecting the flow of the document

5

footer

For identifying a footer for the nearest ancestor bodysectionarticle, or asideelement

5

form

For designating a form to collect data for submission

accept-charset

For identifying the character encoding to be used with the form submission (defaults to the page's character set)

action

For giving the URL of the script that will process the form data

autocomplete

For preventing the browser from providing/remembering autocompletion values when the attribute is set to "off" (the default is "on"; that is, autocompletion is allowed by default)

5

enctype

For making sure files are sent to the server in the proper format

method

For specifying how data should be sent to the server

name

For providing the form with a name for use later

novalidate

For allowing the form to be submitted without validation

5

target

For identifying the target window or iframe of the form's submission

*

h1, h2, h3, h4, h5, h6

For creating headings

head

For creating the head section, which contains information about the page, including the title, author, keywords, style sheets, and scripts

header

For identifying a group of introductory content or navigational aids

5

hgroup

For identifying the heading of a section when a heading has multiple levels

5

hr

For identifying a paragraph-level thematic break

*

html

For identifying a text document as an HTML document

manifest

For specifying an application cache manifest that is used when the page is offline

5

i

For marking a span of text that is in an alternate voice or mood or that is otherwise offset from the normal prose in a manner indicating a different quality of text

*

iframe

For creating a nested browsing context

*

name

For specifying the name of the iframe, to be used as a target

sandbox

For specifying additional restrictions on the content of the iframe, for security purposes

5

seamless

For specifying whether the iframe should appear to be part of the containing page

5

src

For specifying the URL of the initial page

srcdoc

For specifying the URL of the initial page

5

width, height

For specifying the size of the iframe

img

For inserting images on a page

alt

For offering alternate text that is displayed if the image is not and that is for users of assistive devices

crossorigin

For allowing images from third-party sites (that allow cross-origin access) to be used with the canvas element

ismap

For indicating that the element provides access to a server-side image map (the element must be a descendant of an a element)

src

For specifying the URL of an image

usemap

For specifying the client-side image map that should be used with the referenced image

width, height

For specifying the size of an image so that the page is loaded more quickly, or for scaling

input

For creating form elements

accept

For informing the browser what file types will be accepted if the input type is "file"

alt

For providing a textual alternate if the input type is "image"

autocomplete

For preventing the browser from providing/remembering autocompletion values when the attribute is set to "off" (the default is "on"; that is, autocompletion is allowed by default)

5

autofocus

For specifying that the input is to be focused as soon as the page is loaded

5

checked

For marking a radio button or checkbox by default

dirname

For identifying the direction of the entered text

5

disabled

For indicating that the input is not available in the current state

form

For associating the element with a form that it is not a part of

5

formaction

For overriding the form's action attribute

5

formenctype

For overriding the form's enctype attribute

5

formmethod

For overriding the form's method attribute

5

formnovalidate

For overriding the form's novalidate attribute

5

formtarget

For overriding the form's target attribute

5

list

For associating the input with a datalist

5

max, min

For indicating the input element's allowed range of values

5

maxlength

For specifying the maximum number of characters that can be entered in an input element

multiple

For specifying whether the user can be allowed to enter more than one value

5

name

For identifying data collected by an element

pattern

For providing a regular expression against which the input element's value is checked

5

placeholder

For providing a hint to aid in data entry

5

readonly

For keeping visitors from changing certain form elements

required

For identifying that the element must not be blank to submit the form (not allowed when the input type is "hidden," "image," or some button types)

5

size

For specifying the length of a text or password box

src

For specifying the URL of an active image

step

For controlling the granularity and specificity of allowed values

5

type

For specifying if a form element is a text box, password box, radio button, checkbox, hidden field, submit button, reset button, active image, date/time box, number box, or color box; for selecting from a range of values; or for entering a telephone number, email address, or set of search terms

*

value

For specifying the default data in a form element

width, height

For specifying the dimensions of the input (only allowed when the input type is "image")

*

ins

For marking an addition to the document

cite

For referencing a URL that explains the change

datetime

For specifying the time and date of the change

kbd

For marking user input

keygen

For generating a public and private key pair

5

autofocus

For specifying that the keygen element is to be focused as soon as the page is loaded

5

challenge

For generating a challenge to go along with the key pair

5

disabled

For indicating that the element is not available in the current state

5

form

For associating the element with a form that it is not a part of

5

keytype

For identifying the kind of key pair to be generated

5

name

For identifying the data that is gathered

5

label

For labeling form elements

for

For specifying which form element the label belongs to

form

For associating the element with a form that it is not a part of

5

legend

For labeling fieldsets

li

For creating a list item

value

For determining the initial value of the list item (if it is the child of an ol)

*

link

For linking to an external style sheet or other external resource

href

For specifying the URL of the resource

hreflang

For specifying the language of the linked resource

5

media

For defining a style sheet's targeted media types and/or media features

rel

For identifying the kind of link

sizes

For identifying the size of the referenced icon (for use only when the rel attribute is "icon")

5

title

For labeling an alternate style sheet or other resource

type

For noting a resource's MIME type (only required if the link type is not "text/css")

map

For creating a client-side image map

name

For naming a map so it can be referenced later

mark

For highlighting text for reference purposes due to its relevance in another context

5

math

For embedding MathML in the page

5

menu

For containing a list of commands

*

label

For labeling the menu

5

type

For identifying the kind of menu being used: "context," "list" (default), or "toolbar"

5

meta

For associating various kinds of metadata with the page

charset

For identifying the character encoding of the page itself

5

content

For adding extra information about the page itself

http-equiv

For creating automatic jumps to other pages, setting the default scripting language, and declaring the character encoding

name

For identifying extra information about the page

meter

For representing a measurement within a known range

5

high, low

For specifying a range of values as being "high" or "low"

5

max, min

For identifying the maximum and minimum allowable values

5

name

For identifying the data that is gathered

5

optimum

For identifying the optimum value

5

value

For indicating the current value of the meter (required)

5

nav

For identifying a section of a page that links to other pages or to parts within the page

5

noscript

For providing alternatives to scripts

object

For embedding objects in Web pages

data

For identifying the source of the multimedia file to be embedded

form

For associating the element with a form that it is not a part of

5

name

For identifying the object (e.g., so it can be scripted)

type

For noting the object's MIME type

typemustmatch

For indicating that the resource specified in the object's data attribute must have the same MIME type as identified in the object's type attribute (allowed only if the object's data and type are both specified)

usemap

For indicating whether the object has an associated image map

width, height

For specifying the dimensions of the object's box

ol

For creating ordered lists

reversed

For specifying whether the list is descending (. . . , 3, 2, 1)

5

start

For specifying the initial value of the first list item

*

type

For specifying the kind of numerals that should begin each list item

*

optgroup

For grouping a set of option elements under a common label within a select element

disabled

For indicating that the element is not available in the current state

label

For labeling the group of options

option

For creating the individual options in a select or datalist element

disabled

For indicating that the element is not available in the current state

label

For specifying how the option should appear in the menu

selected

For making a menu option be selected by default in a blank form

value

For specifying the initial value of a menu option

output

For representing the result of a calculation

5

for

For creating an explicit association between the result of a calculation and the values that went into the calculation

5

form

For associating the element with a form that it is not a part of

5

name

For identifying the data that is gathered

5

p

For creating a paragraph

param

For setting properties of an object

name

For identifying the kind of property

value

For setting the value of the named property

pre

For representing a block of preformatted text

progress

For identifying the completion progress of a task

5

max

Must be a valid floating-point number greater than zero (if present)

5

value

Must be a valid floating-point number equal to or greater than zero (and less than or equal to the value of the max attribute, if it is present)

5

q

For quoting short passages from another source

cite

For giving the URL of the source of the quote

rp

For providing parentheses around a ruby text component of a ruby annotation in browsers that don't support ruby annotations

5

rt

For marking the ruby text component of a ruby text annotation

5

ruby

For allowing text to be marked up with ruby annotations

5

s

For identifying text that is no longer accurate or no longer relevant

*

samp

For representing sample output from a program or computing system

script

For adding "automatic" scripts to a page

async

For influencing script loading and execution

5

charset

For specifying the character set an external script is written in

defer

For influencing script loading and execution

src

For referencing an external script

type

For specifying the scripting language the script is written in (only required if the script type is not "text/javascript")

*

section

For identifying a section of a document

5

select

For creating form control for selecting from a set of options

autofocus

For specifying that the select element is to be focused as soon as the page is loaded

5

disabled

For indicating that the element is not available in the current state

form

For associating the element with a form that it is not a part of

5

multiple

For allowing users to choose more than one option in the menu

name

For identifying the data collected by the menu

required

For identifying that the user must select one of the options in order to submit the form (the first child option element must be a placeholder or an empty value)

5

size

For specifying the number of items initially visible in the menu (and for displaying the menu as a list)

small

For representing side comments such as small print

*

source

For identifying multiple alternative media resources within an audio or video element

5

crossorigin

For setting cross-origin request credentials

5

media

For identifying the intended media type of the resource

5

src

For identifying the URL of the audio or video file to play

5

type

For noting a resource's MIME type

5

span

For wrapping content in an element that has no intrinsic semantic meaning

*

strong

For indicating strong importance of the element's content

*

style

For embedding style information in a page

media

For indicating a style sheet's purpose

scoped

For applying styles only to the descendants of the element's parent

5

type

For indicating a style sheet's MIME type (only required if the style type is not "text/css")

*

sub

For creating subscripts

summary

For identifying a summary, caption, or legend for the contents of its parent detailselement

5

sup

For creating superscripts

svg

For embedding Scalable Vector Graphics in the page

5

table

For creating tables

tbody

For identifying the body of the table; in contrast with the header (thead) or footer (tfoot)

td, th

For creating regular and header cells, respectively, in a table

colspan

For spanning a cell across more than one column

rowspan

For spanning a cell across more than one row

scope

For identifying to which rows, columns, rowgroups, or columngroups a th applies

textarea

For creating text block entry areas in a form

autofocus

For specifying that the text area is to be focused as soon as the page is loaded

5

dirname

For identifying the direction of the entered text

5

disabled

For indicating that the element is not available in the current state

form

For associating the element with a form that it is not a part of

5

maxlength

For specifying the maximum number of characters that can be entered in a textarea

name

For identifying the data that is gathered with the text block

placeholder

For providing a hint to aid in data entry

5

readonly

For protecting a text area's contents

required

For indicating that the element must not be blank in order to submit the form

5

rows, cols

For specifying the number of rows and columns in the text block

wrap

For specifying the use of soft or hard wraps when content of field is submitted

5

tfoot, thead

For identifying the footer and header area of a table

time

For specifying a date, a time, or both

5

datetime

For providing a machine-readable version of the time or date expressed in the element's text

5

pubdate

For specifying the publication date and time of the element's ancestor article orbody element

5

title

For creating the title of the page (required)

tr

For creating rows in a table

track

For specifying external timed text tracks for the parent audio or video element

5

default

For indicating which track is the default

5

kind

For identifying whether the track is "subtitles," "captions," "descriptions," "chapters," or "metadata"

5

label

For providing a user-readable name for the track

5

src

For identifying the URL of the track's data

5

srclang

For identifying the language of the track's data

5

u

For displaying a span of text with an unarticulated, though explicitly rendered, non-textual annotation

*

ul

For creating unordered lists

var

For marking text as a variable name

video

For embedding videos, movies, and captioned audio files

5

autoplay

For telling the browser to start playing the video file as soon as it can

5

controls

For telling the browser to provide controls for the video element

5

crossorigin

For setting cross-origin request credentials

5

loop

For telling the video file to start over without interruption upon reaching its end

5

mediagroup

For associating multiple media files together

5

muted

For controlling the default state of audio output

5

poster

For specifying the URL of an image to use as a placeholder while media loads, or in case of an error loading

5

preload

For specifying whether the browser can begin downloading the media file before the visitor starts playing it

5

src

For identifying the URL of the video file to play

5

width, height

For specifying the dimensions of the video

5

wbr

For identifying an appropriate place to insert a line-break into a word without hyphenation

5