Introduction
Having completed a web application, or website, in your native language, comes the necessity to localize it in another language, to make it accessible outside your country too. If you have hard-coded strings in your pages (which you've probably done, especially for labels and/or all-purpose messages), a task like this could be pretty eerie to accomplish (primarily depending on project size, or complexity level).
Here we'll see a fast and easy method to alter a webpage's DOM, using a custom resource file to modify our strings inside predetermined elements. We'll see how to do that using plain JavaScript first, then jQuery.
A simple page
Here follows the HTML of a simple page, showing some element's values written in Italian. Please note that all the elements have an ID. That's fundamental for when we come to the scripting part.
- <html>
- <head>
- <title>Translate Website/Webapp with JS and XML</title>
- </head>
-
- <body>
- <h1 id="AppTitle">Titolo applicazione</h1>
-
- <span id="GenText">Testo generico con fini dimostrativi</span><br/>
- <span id="EndText">Testo di chiusura</span>
-
- <div id="DivText">
- Testo contenuto in un div.
- </div>
- </body>
- </html>
Opening it in a browser, our page will resemble the following:
Making a string resource file
In a hypothetical string resource file, we want to introduce all of our app's strings. We can create a set of XML entities having attributes complying with our HTML elements. In other words, exploiting the JavaScript function to access DOM's elements by their ID, we could think of pairing a given HTML ID with its XML counterpart. For example, based on the previous page example, we could jot down a resource file like the following:
- <strings>
- <string id="AppTitle" en = "Application's Title"/>
- <string id="GenText" en = "Generic text with demonstrative means"/>
- <string id="EndText" en = "Closing text"/>
- <string id="DivText" en = "Div contained text"/>
- </strings>
For each string entity, we've defined two attributes. The first, id, corresponds to a specific ID in HTML code, while the second one, "en", contains an English translation of our elements. The logic behind this is simple. When our page finishes loading, we need a JavaScript to be fired up in order to read our DOM's IDs, replacing their innerHTML with the one specified in XML "en" attribute.
We'll save the preceding example as "translate.xml", for further use.
Replace text using JavaScript
The first function we'll provide is about reading our XML file, using XMLHttpRequest (or XMLHTTP, if on IE). Check the following:
- function loadXMLDoc(filename){
- if (window.XMLHttpRequest){
- xhttp = new XMLHttpRequest();
- } else {
- xhttp = new ActiveXObject("Microsoft.XMLHTTP");
- }
- xhttp.open("GET",filename,false);
- xhttp.send();
- return xhttp.responseXML;
- }
Finally, the localize() function must be fired up after the complete load of our page, to ensure all the elements will be rendered/accessible. We could simply add an explicit call to localize() after the closing of body tag, in the following way:
-
- </body>
-
- <script>
- localize();
- </script>
- </html>
You could refer to the file "sample01.html" in the source code for the full example. Running our page again, we'll see the text will be replaced as in the following:
Important: It's advisable to run the presented code in a web server environment (IIS or Apache), because the opening of our XML file could end up in a cross-origin request exception otherwise.
Replacing text using jQuery
Using jQuery will result in a more compact script, in which we can rely on asynchronicity and specify to await for a complete load in a single location (typically, the HEAD section). The entire script seen above could be replaced with the following:
- <script src="http://code.jquery.com/jquery-latest.min.js"></script>
-
- <script>
- $(document).ready(function(){
- $.ajax({
- type: "GET" ,
- url: "translate.xml" ,
- success: function(xml) {
- $(xml).find('string').each(function(){
- var item_id = $(this).attr("id");
- $("#" + item_id).text($(this).attr("en"));
- });
- }
- });
- });
- </script>
Here, after finishing the loading of the page, our script will proceed in an AJAX call to our trasnalte.xml file and upon success in accessing it, it will loop through "string" entities, using the "id" and "en" attributes to refer to which DOM element must be targeted and replacing their inner HTML with the one of our choice. Please refer to the "sample02.html" file in the given source code.
Conclusion
Far from declaring the ultimate method to localize a website or webapp, we saw a pratical and quick method to do that. The quality of such an approach resides indisputably in the minimum interventions necessary in the original source code, assuming an ID naming approach has been used at the development stage. I hope you'll find it useful.