Reputation: 9590
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>
Upvotes: 8
Views: 5669
Reputation: 6638
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 var
declaration 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.
Upvotes: 7