I've been having issues using google translator directly on my sveltekit web app using the following code
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
// googleTranslateElementInit()
</script>
I've tried several approaches, for example putting the code in <svelte:head></svelte:head>
but yet it's kept appearing and disappearing.
Please how can I achieve this,
Note I'm using Static adapter, thanks in advance
I had to load the script manually after mounting of component. It works with SvelteKit too.
onMount(() => {
loadTranslate()
setTimeout(function () {
googleTranslateInit()
}, 3000)
})
function googleTranslateInit() {
const checkIfGoogleLoaded = setInterval(() => {
if (google != null && google.translate != null && google.translate.TranslateElement != null) {
clearInterval(checkIfGoogleLoaded)
googleTranslateElementInit()
}
}, 1000)
}
function googleTranslateElementInit() {
new google.translate.TranslateElement({ pageLanguage: 'en' }, 'google_translate_element')
}
function loadTranslate() {
loading = true
if (browser) {
const domElement = document.createElement('script')
domElement.setAttribute('src', '//translate.google.com/translate_a/element.js')
domElement.onload = () => {
loadedTranslate = true
}
document.body.appendChild(domElement)
}
}
</script>
<template>
<div id="google_translate_element" class="mb-2"></div>
</template>