One, a brief introduction
A recent official website project of the company requires internationalization of the page and the realization of switching between Chinese and English. For this reason, I have found some solutions for switching between Chinese and English on the Internet, which are roughly as follows:
1. Use Google's Whole Site Translation Api
- Advantages: just call the interface, you can easily complete the whole station translation, translation accuracy is good.
- Cons: Requires a ladder.
- Reference article: JS code to achieve website translation between Chinese and English
2, write their own Chinese and English comparison table, with JS control
- Advantages: one-to-one translation, so the highest accuracy.
- Disadvantages: need to write a large number of Chinese-English comparison tables, only suitable for a small number of fixed translation.
- How to switch between Chinese and English on HTML page?
Because the company's requirement is to translate the whole site, and there is news in the official website, that is, there is a lot of unpredictable data, and considering the rich text data is not easy to translate. So, on balance, the first option is the most suitable, but unfortunately, need a ladder, no way, but not to find a way out. Fortunately, Microsoft has an Api similar to Google's whole Site Translate:
The Translator Web Widget API
In fact, The Demo provided by Microsoft is also very simple, divided into the following steps:
- Introduce The Translator Web Widget API
- Listening to the dom to load, call Microsoft. The Translator. Widget. The Translate () site translation.
Second, the implementation
1. Encapsulate language.js
According to the above research on the Demo provided by Microsoft, we further encapsulate this, because the Chinese and English switch is generally a click, the unification of each page in the future needs or does not need to be translated, which needs to record a state value, here select THE STORAGE provided by HTML5 to store this state, And provides a way out to modify the state and refresh the page. Therefore, the js (language.js) is written as follows:
2. Write test pages
Write a test page (test.html). To use language.js above, you must do the following three steps:
- Set the page encoding to UTF-8
- Introduce jquery and language.js
- Set the click event of the button to call the Translate () function.
Let's try the effect, but I think it's ok
Language.js (zh-chs to En). If your project needs to convert to another language, you can customize language.js.