If you have ever used
googles translate API, it can quickly become a love hate relationship. You love the features it provides, but you begin to hate that fact that google's server are slow and flaky for loading the libraries that they recommend.
This situation was getting especially annoying yesterday, as the load time of my application (that is getting continually re-loaded while I'm working on it) was getting worse and worse, and google's API's was the culprit.
So after some further reading on that page, I realized that the translation call was really just a simple HTTP request with the correct parameters.. no need for huge google framework API etc.
So here's the ~20 line javascript to replace the slow loading 50k+ library that google recommends....
/**
* usage
* gtranslate('hello', 'en', 'es', function (res) {
* if (typeof(res) == 'object') { return; } // failure
* console.log(res); // success...
* });
*/
function gtranslate(str, src, dest, cb)
{
var x = new Roo.data.ScriptTagProxy({
url: 'http://ajax.googleapis.com/ajax/services/language/translate',
callbackParam : 'callback'
});
x.load(
{
v: '1.0',
q : str,
langpair : src + '|' +dest,
}, // end params.
{ // reader
readRecords : function (o) {
if (!o.responseData) {
return o;
}
return o.responseData.translatedText;
}
},
function (result) {
cb(result);
},
this,
[]
);
}