JavaScript Localization: A Step-by-Step Guide

Table of Contents

Language should not be a barrier to growing your business in the current interconnected world, especially if you are doing online business. Multi-language support is, therefore, a functional feature for applications, software, and websites to enhance user accessibility. Website developers can choose from various programming languages to build multi-lingual sites. In this article, Thao & Co. takes you through a step-by-step guide for simple and fast JavaScript localization for your website.

What is JavaScript Localization?

First, we must understand website localization strategy: this process involves translating every component of a website to fit the linguistic and cultural preferences of the target audience. These components may include texts, audio, pictures, symbols, colors, signs, and sometimes even the layout, interface, and functionality.

Through content adaptation, website localization aims to provide the target audience with a unique experience that feels natural and culturally relevant, making the website more approachable.

Within the field of website localization, JavaScript Localization refers to the process of building JavaScript codes that can dynamically accommodate content in multiple languages. In other words, a localized JavaScript website can support multilingual content by adapting its interface and text to cater to users speaking different languages. For optimal results, JavaScript localization should be performed by seasoned experts.

Multi-lingual JavaScript allows you to adapt your website code to support multilingual content, often incorporating third-party libraries. You can find several existing JavaScript libraries designed to handle various aspects such as loading language files (often in JSON format), managing translations, detecting the default language, and detecting non-existing phrases, among others.

How to Create Multi-language Functions for Your JavaScript Website

Thao & Co. - javascript localization

To create a multi-language function for your Javascript website, you can use the multi-language.js library to simplify adding multilingual support. Here’s how you can do it:

  1. Method 1: Use a content delivery network (CDN)

Sao chép và dán đoạn mã sau vào trong thẻ <head> của website

<script src=”https://cdn.jsdelivr.net/gh/askask11/[email protected]/dist/multi-language.min.js” integrity=”sha256-xL5PbSBwYLKYaUvdDP2S/lnF9s3oAPm/92GnACZBe2c=” crossorigin=”anonymous”></script>
  1. Method 2: Serve it manually

Download multi-language.js and serve the library from your origin. Note: Be sure to check the repository releases to download the source code. Unzip it when finished. Navigate to directory dist in your root folder, place the multi-language.js file (or multi-language.min.js) in your website project folder, and plug the code into your website.

<script src=”js/multi-language.min.js”></script>

Next, follow these instructions to start localizing your web pages with JavaScript:

Step 1: Define your language codes

The first thing to do is to assign a short code for each language. The common practice is using two or three letters to represent the full name of the language. For example, “en” can stand for English, “ko” stands for Korean, and “vi” stands for Vietnamese.

Refer to the ISO 639-1 language codes for a standardized and consistent code usage that is internationally recognized.

Step 2: Index your webpage

Give ID to all webpage elements that will be in direct contact with the text. You can also wrap your text with the span element. For example,

  <!––The id will be used to locate the element.––>
<div id=”c1″>Internationalization is very important, indeed.</div>

<!--You should label text-only children elements, and use their id for reference later.-->

  <div>

    <img src="img/image.png" >

    <!--Label the element that is directly in contact with the text.-->

    <span id="c2">

      Do you really want to translate me?

    </span>

    <!--You may also include simple mark-ups for the text-->

    <span id="c3">

      Yes, because <strong>you<strong> are <u>not</u> fancy enough.

    </span>

  </div>

Step 3: Create your JSON translation Sheet

A translation sheet is a structured data representation used for managing translations. It typically takes the form of a JSON Array containing the element IDs in the document and their corresponding translations in different languages. This library reads the translation sheet when your webpage loads and applies the translations to your content accordingly.

Quý vị có thể viết trang tính này vào một tệp JSON bên ngoài hoặc viết trực tiếp nó vào trong mã bằng một thẻ như <script id="translation-sheet" type="application/json">** BẢN DỊCH **</script> trong phần Trang HTML cần dịch. It’s crucial to place the translation sheet before the code relying on it. Always make sure your translation sheet is loaded and available before activating any scripts that use the translated phrases.

  1. Structure of a translation sheet

A translation sheet is a data structure represented as a JSON Array. Each element in the translation sheet is an item to be translated. These elements are structured as JSON Objects within the array.

  1. Example of a translation sheet
[
{

    "id":"**THE ID OF THE TEXT ELEMENT**",

    "langs":{

      "en":"Hello!",

      "es":"¡Hola!",

      "zh":"你好(nihao)!"

    }

  },

  {

    "id":"**THE ID OF ANOTHER TEXT ELEMENT**",

    "langs":{

      "en":"Goodbye",

      "es":"Adiós",

      "zh":"再见"

    }

  },

  {...},

  {...},

  ......

]
  1. Example of a complete translation sheet in HTML
 <img src=”welcome.png”>
<div id="welcome-txt">

  Hello! (I am the default text)

 </div>

<br>

...

<br>

<input placeholder="Enter Your Name" id="name-input">

<button id="farewell-btn" title="Thank you for visiting!" onclick="alert('Have a good day!');">

  Goodbye!

</button>
  1. Example of a complete JSON translation sheet
[

  {

    "id":"welcome-txt",

    "langs":

    {

      "en":"Hello!",

      "es":"¡Hola!",

      "zh":"你好(nihao)!"

    }

  },

  {

    "id":"name-input",

    "attr":

    {

      "placeholder":

      {

        "en":"Please enter your name",

        "es":"Por favor ingrese su nombre aquí",

        "zh":"请输入您的姓名"

      }

    }

  },

  {

    "id":"farewell-btn",

    "langs":

    {

      "en":"Goodbye",

      "es":"Adiós",

      "zh":"再见"

    },"attr":

    {

      "title":

      { 

        "en":"Thank you for visiting.",

        "es":"Gracias por su visita.",

        "zh":"谢谢访问!"

      },"onclick":

      {

        "en":"alert('Have a good day!');",

        "es":"alert('¡Que tenga un buen día!');",

        "zh":"alert('祝您有美好的一天!');",

        "ko":"alert('좋은 하루 되세요!');",

        "vi":"alert('Chúc bạn ngày mới tốt lành');"

      }

    }

  }

]

Step 4: Construct your Multi-language instance

To enable multi-language support on your website, you must construct a translator and place it at the bottom of your HTML body. The MultiLanguage constructor accepts 3 parameters, but you don’t have to provide any parameters. Those include:

  1. defaultLanguage: a default language assigned for users who have not set any preferred language. Translations must be available for this language across all elements. If your default language code is not “en,” make sure you specify the default language for your website.
  2. externalJSON: the translation sheet that you want to load into the translator. By default, if you don’t explicitly provide any translation sheet, the system will load an empty array. You can load multiple translation sheets by calling the method addSheet(translationSheet) after constructing this instance.
  3. select: The <select> element is like a dropdown menu. It lets users pick an option from a list of supported languages. Each option represents a language. The value attribute of the selected <option> tells the system which language to use. You can have multiple language dropdowns on your site by calling a special method registerSelect(select).

Step 5: Load the translation sheet into the Multilanguage instance

Imagine you have a translation sheet with all of your translations and you want your website to use these translations. Here’s how you can do it:

var xhr = new XMLHttpRequest(); //Create an xhr instance

var translator = new MultiLanguage(); // define translator, create a default instance

xhr.open("***HTTP METHOD TO USE***","***LINK TO YOUR SHEET.json***"); // Define target file and HTTP method to use.

xhr.onreadystatechange=(e)=>{

  if(xhr.readyState === 4 && xhr.status === 200)

  {

    var jsonResponse = JSON.parse(xhr.responseText); // get response text and parse it into JSON.

    translator.addSheet(jsonResponse);

  }

}

xhr.send()

If you have written directly in your HTML, you can grab them and parse the content into a JSON Object:

var json = JSON.parse(document.getElementById("translation-sheet").innerHTML);

var translator = new MultiLanguage("en",json);

You can repeat these steps for multiple sheets but DON’T load the same sheet more than one time.

Step 6: Register select elements for language control

Quý vị có thể cho phép người dùng kiểm soát ngôn ngữ trang bằng cách xác định phần tử <select> trong trang. Sau đó, đăng ký <select> cho trình dịch hoặc chuyển đối tượng Element của lựa chọn đó cho hàm tạo. Otherwise, manually call the translate(language) function to change the language.

Here’s how you can do HTML select:

<select id="languages">

  <option value="en">

  English (Default)

  </option>

  <option value="zh">

  简体中文

  </option>

</select>

 To register (select), select the translation version:

var translator = new MultiLanguage(select=document.getElementById("languages")); // you may pass it to the constructor

or,

var translator = new MultiLanguage();

translator.registerSelect(document.getElementById("languages")) // You may call method "registerSelect" to register it

You can register as many select elements as you need. But be careful, don’t register the same select element more than once.

The select element you register can control the language settings for your entire website. When users pick a language from the dropdown, everything on the website will change to that language.

All done! You now have a multi-language website!

Translation APIs for JavaScript websites: Pros and cons

API stands for Application Programming Interface, a set of rules and protocols to facilitate communication between a server and a web browser. Language Translation APIs auto-translate website content into the user’s preferred language by pulling data from either a third-party website or software. For instance, the Google Translation API collects language data from Google, enabling automatic translation.

Despite their usefulness for website localization effectively, Translation APIs come with certain constraints. Wonder if a Multi-Language API could be a good choice for your website? Consider the advantages and drawbacks:

Benefits

  1. Automation: APIs allow all features to function automatically, improving speed, workflow, and seamless task management.
  2. Significant data resource: APIs provide an extensive database of languages gathered from multiple external sources.
  3. Flexible integration: With APIs, you can access information from any websites and applications that grant permission.
  4. Real-time update: While the data is pulled from an external source, APIs can automatically update the information whenever the source data is updated.
  5. The number of available APIs: Major players like Google or Facebook now offer APIs to directly connect, collect, and update data from their sites.
  6. APIs support MVC (Model-View-Controller) components such as routing, controller, filters, etc.

Limitations

  1. ● Incorporating APIs requires a certain level of technological expertise and experience in back-end website development.
  2. ● Some APIs charge licensing fees for professional use.
  3. ● Careful attention regarding confidentiality is needed throughout the API implementation process.

Thao & Co.: Your Trusted Partner for Website Localization

Investing in a full-package service of multilingual website is crucial for businesses to achieve global reach. Global integration has helped businesses thrive as they expand their markets, enabling engagement across regions, tapping into the global network, and many more. As beneficial as it is, implementing effective website localization for your business involves advanced knowledge and extensive expertise.

Translation Services - Thao & Co.

Serving as a communication bridge for +200 enterprises over the years, Thao & Co. is proud to be a part of your international success story! As a tech-enabled translation company, we offer creative and cost-effective solutions to help individual and enterprise clients convey their messages across languages through our Website Translation + Localization services and Customized Integration + Linguistic Review services.

Thao & Co.’s team of expert linguists, boasting years of experience in the Advertising and Marketing industry, guarantees you high-quality translations that resonate with your target audience on a deeper level.

Our flexible B2B solutions are highly secured – a streamlined workflow made possible through our proprietary platform. We deliver professional services to exceed your expectations in terms of quality, speed, and client care.

Our Website Localization goes beyond translation: we can help you integrate everything into your web pages. For the website to operate smoothly, we believe translations must be specifically tailored to its features and interface.

Integration, primarily as a manual process, demands specialized knowledge and substantial time investment. However, this effort enables businesses to maintain control, mitigate UI/UX risks, and enhance security measures.

In response to the growing demand for professional website translation services, Thao & Co. offers our Customized Integration and Linguistic Review solutions. Our Custom Integration service facilitates natural, context-appropriate translations compatible with your website features. This boosts user experience and ensures information privacy while saving you time and effort in the long run.

Key takeaways

JavaScript localization is considered one of the most effective methods for multi-language websites. However, the development stage can take a long time to complete and demand a certain level of technical expertise. For optimal results, prioritize engaging a professional translation agency that can also assist you with the integration process.

Say goodbye to localization headaches and get your website professionally translated and integrated today! For a free consultation and itemized quote for our website localization services, connect with our specialists at Thao & Co. via our Get a Quote page.

Source: Thao & Company
Professional Translation and Localization Services in Vietnam
Where Precision Meets Quality Standards
Get in touch
Let us know how we can help!
Our industries
Healthcare
We provide accurate translations of items such as clinical instructions, medical records, articles, product labels and questionnaires.
Advertising + Marketing
Get your message across in any language when we translate your informational materials, instructions and simple promotional content.
Banking + Finance
As you tap new markets, we can translate sales materials, emails, job applications, CVs, legal documents, and entire banking/trading platforms and apps.
Legal
Get fast, precise translation of legal documents, contracts, memos, emails and other forms of communication.
Real Estate + Construction
Our translators have sufficient familiarity with architecture, construction, real estate and civil engineering to help translate relevant documents.
Retail + E-commerce
If you’re selling to global markets, let us translate your sales materials, company announcements and meeting minutes for your international partners.
Travel + Tourism
We can provide general translation of content for internal communications and customer-facing text for hotels, restaurants, travel guides and more.
Entertainment
Relying on our experience translating films, plays and commercials, we give careful attention to word selection and meaning in every project.
Automotive + Aerospace
Look to our specialized linguists to translate and localize user guides, CAD drawings, repair manuals and business contracts.
Manufacturing
Get precise translation of technical terminology whether for instructions, safety, quality control or regulatory compliance.
Manufacturing
Explore new markets for your games once we translate the rules, instructions, storyline, dialog, graphics and technical details.
Education
Empower global education with our translation and localization services. Available for academic transcripts, diplomas, degrees, certificates, websites, apps, and more.
Technology
Our expert localization services are here to get your tech materials, websites, apps, software and other digital products into new markets.
Ready to take the next step? Tell us about your project.

Get a quote