Skip to content

Script doesn't run when navigating between pages #344

Open
@phillipmohr

Description

@phillipmohr

📚 What are you trying to do?

I'm using iubenda to implement legal pages. The script looks for an element like this:

<a href="https://www.iubenda.com/privacy-policy/123456789" class="iubenda-nostyle iubenda-noiframe iubenda-embed iubenda-noiframe " title="Privacy Policy ">Privacy Policy</a>

And replaces it with the content.

This is the original script: => https://cdn.iubenda.com/iubenda.js

This is how iubenda wants me to implement it:

<script type="text/javascript">(function (w,d) {var loader = function () {var s = d.createElement("script"), tag = d.getElementsByTagName("script")[0]; s.src="https://cdn.iubenda.com/iubenda.js"; tag.parentNode.insertBefore(s,tag);}; if(w.addEventListener){w.addEventListener("load", loader, false);}else if(w.attachEvent){w.attachEvent("onload", loader);}else{w.onload = loader;}})(window, document);</script>

I've added it to my component, like so: useScript('https://cdn.iubenda.com/iubenda.js')

It's working when reloading the page with STRG + F5, however, it does not load/replace the content when navigating between pages (e.g. navigating from page A which uses this component to page B which uses the same component)

ChatGPT suggested this ugly workaround but I was wondering if there is another solution?

useScript('https://cdn.iubenda.com/iubenda.js')

const reloadIubendaScript = () => {
  const existingScript = document.querySelector('script[src="https://cdn.iubenda.com/iubenda.js"]');
  if (existingScript) {
    existingScript.remove();
  }

  const newScript = document.createElement('script');
  newScript.src = 'https://cdn.iubenda.com/iubenda.js';
  newScript.async = true;
  document.body.appendChild(newScript);
};

onMounted(() => {
  reloadIubendaScript();
});

watch(
  () => route.path,
  () => {
    reloadIubendaScript();
  }
);

🔍 What have you tried?

  • Docs
  • loading the script manually inside onMounted
  • Trying to load script with addEventListener('DOMContentLoaded')

ℹ️ Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions