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.
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.
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:
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>
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:
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.
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>
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.
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.
[
{
"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":"再见"
}
},
{...},
{...},
......
]
<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>
[
{
"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');"
}
}
}
]
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:
<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).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.
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!
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:
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.
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.
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.