Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to asynchronously load Google Translate widget for your website?

Is there a way to asynchronously load Google Translate widget for your website?

I tried putting this on the bottom of my page, but the #google_translate_element container was still empty.

<!-- Asynchronous Google Translate -->
<script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar,bg,bn,de,el,eo,es,en,fr,hi,id,it,iw,ja,ko,pl,pt,ru,th,tr,vi,zh-CN', layout: google.translate.TranslateElement.InlineLayout.SIMPLE, gaTrack: true, gaId: 'UA-1234-1'}, 'google_translate_element');
}

(function() {
  var googleTranslateScript = document.createElement('script');
  googleTranslateScript.type = 'text/javascript';
  googleTranslateScript.async = true;
  googleTranslateScript.src = '//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';
  ( document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] ).appendChild( googleTranslateScript );
})();
</script>
like image 507
Geoff Avatar asked Mar 13 '13 06:03

Geoff


People also ask

Is Google Translate widget free?

Who can get the Google Translate Widget for free? The Google Translate Website Translator has been made available at no cost for government, nonprofit, and non-commercial use only. This is only being offered for use by websites with a primary focus on COVID-19 response that fit the following categories: government.


1 Answers

It seems that you have several problems in your code. But your basic idea is sound.

Assuming that <div id="google_translate_element"></div> is defined before the the script tag, the following should work:

<!-- Asynchronous Google Translate -->
<script type="text/javascript">
  function googleTranslateElementInit() {
    new google.translate.TranslateElement({pageLanguage: 'en',
      includedLanguages: 'ar,bg,bn,de,el,eo,es,en,fr,hi,id,it,iw,ja,ko,pl,pt,ru,th,tr,vi,zh-CN',
      layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
      gaTrack: true, gaId: 'UA-37652767-1'}, 'google_translate_element');
  }

  var googleTranslateScript = document.createElement('script');
  googleTranslateScript.type = 'text/javascript';
  googleTranslateScript.async = true;
  googleTranslateScript.src = 'http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';
  ( document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] ).appendChild(googleTranslateScript);
</script>

At least it worked for me when I placed it all in a HTML file and loaded into chrome.

Of course it would be possible to place the vardeclaration and following lines in a $(document).ready function (or in some other manner if you do not use jQuery). Then the order between div and script would no longer be of consequence.

like image 122
fredrik Avatar answered Nov 15 '22 17:11

fredrik