This code below will not load the script from Google's servers until the "Load Google Translate" button is pressed.
<html>
<head>
<script>
function loadGoogleTranslate() {
var scriptTag = document.createElement('script');
scriptTag.type = "text/javascript";
scriptTag.src = "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
var head = document.getElementsByTagName('head')[0];
head.appendChild(scriptTag);
}
function googleTranslateElementInit() {
// Hide the section containing the "Load Google Translate" button
var beforeLoadSection = document.getElementById('before-load');
beforeLoadSection.style.display = 'none';
// Set up Google Translate now that their script has loaded
new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
// Show the section containing the Google Translate element
var afterLoadSection = document.getElementById('after-load');
afterLoadSection.style.display = '';
}
</script>
</head>
<body>
<div id="before-load">
<button onclick="window.loadGoogleTranslate()">Load Google Translate</button>
</div>
<div id="after-load" style="display:none">
<div id="google_translate_element"></div>
</div>
</body>
</html>
You can verify that the Google script is not loaded until the button is clicked by watching network traffic (in the "Network" tab of Chrome's DevTools for example).
Note you can also just create a link like this one that users can click on to access a translated version of your page, no fancy Javascript required:
https://translate.google.com/translate?hl=&sl=en&tl=ar&u=https%3A%2F%2Fstackoverflow.com%2Fq%2F55643969%2F3063273
I bolded the parts you'll need to worry about:
- en is the "from" language (English in this case)
- ar is the "to" language (Arabic in this case)
- long string of text is the URL-encoded form of the page to translate. Google "URL encode" if you want to learn how to do that. Javascript has a built-in function that might help
P.S. You probably got a downvote from someone because they don't like "write-my-code" types of questions. If you had instead included a minimal, complete, and verifiable example (MCVE) then you probably wouldn't have been downvoted, but creating an MCVE can be really difficult if you have no idea where to even start. Here's some additional reading on that subject if you want to learn more about the culture around here: https://meta.stackoverflow.com/a/345249/3063273
P.P.S. If you want to use the above fancy-pants Javascript code, keep in mind that you can't use it in an iframe
. If you don't know what an iframe
is then don't worry about this.