1/28/2024 Google Translate Notes
Before now, Google translate was operating via the code below inserted into the footer. There was an issue with the translate feature not appearing on the initial load of the site. Code Below for future reference.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> <script> $(document).ready(function(){ $('<div id="google_translate_element"></div>').appendTo('div.header-inner'); }); </script> <script type="text/javascript"> function googleTranslateElementInit() { new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL}, 'google_translate_element'); } </script> <script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
I assumed the problem was that the (document).ready function caused the jQuery “appendto” to run after the Google Translate script ran. Because there was no <div id="google_translate_element"></div> for Google translate to modify, the translate code did nothing until a cached reloaded.
This is a weird, squarespace specific problem. I attacked this from several angles until I discovered that it was completely valid to call the external translate script from the (document).ready function. This apparently works because the call-back, cb, at the end of the script is the triggering event.
The footer code has been removed and the two snippets of code have been added via the Code injection panel.
New Header Injected Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> <script> $(document).ready(function(){ $('<div id="google_translate_element"></div>').appendTo('div.header-inner'); $('<script/>',{type:'text/javascript', src:'//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit'}).appendTo('head'); }); </script>
New Footer Injected Code:
<script type="text/javascript"> function googleTranslateElementInit() { new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL}, 'google_translate_element'); } </script>