N
Nuxt9mo ago
Jelena

Rerunning IIFE function from external script added with useHead inside a component

Hi everyone! I have a component in Nuxt 3 application that shows an embeded form. <template> <div :class="['form-embed', classList]" :style="background ? { backgroundColor: background } : ''"> <div :class="wrapper"> <h4>{{ props.data.form_embed_title }}</h4> <p class="text">{{ props.data.form_embed_text }}</p> <div class="form-container"> <div :id="props.data.form_embed_form_id" :lang="locale"></div> </div> </div> </div> </template> <script setup> const { locale } = useI18n(); const props = defineProps({ data: { type: Object, default: () => {} }, }); const { classList, background, wrapper } = useUseStyling(props.data, 'form_embed', false); const scriptSrc = ref(props.data.form_embed_source_id); const scriptRef = ref(null); useHead({ script: [ { id: props.data.form_embed_script_id, src: scriptSrc.value + '?t=' + Date.now(), defer: 'defer', ref: scriptRef, }, ], }); watch(locale, () => { if (scriptRef.value) { scriptRef.value.src = props.data.form_embed_source_id + '?t=' + Date.now(); // Adding a query parameter can help bypass browser caching } }); </script> Script is IIFE function. My question is how can i on language change re-run that IIFE function again. The code above is not working (function is not rerun on language change) The problem is that the script is same for all the languages, what changes is locale in this bit of a code: <div :id="props.data.form_embed_form_id" :lang="locale"></div> but i need to rerun that IIFE function in script that is loaded in head again to form to be shown in different language when language is changed. Any ideas? Thanks!
1 Reply
Tirius
Tirius9mo ago
Dynamically changing script src won't force browser to load and run it again, I think it runs only once and cached by browser. You probably need to add new script tag every time when you need to run your function. And probably it would be better to use vanilla js to add new script tag and remove old one, since I don't think that you can remove script tag with useHead
Want results from more Discord servers?
Add your server