Skip to content
Advertisement

Force Nuxt to run script tag

I have a script on a page:

<script type="text/javascript">app_id="ID_HERE";distribution_key="dist_6";</script><script type="text/javascript" src="https://loader.knack.com/ID_HERE/dist_6/knack.js"></script><div id="knack-dist_6">Loading...</div>

If I go to the page via a NuxtLink in the navigation the script runs, however if I type the URL to the browser address bar it doesn’t.

Is there a way to force the NuxtLink result when the page is accessed directly?

The script tag is coming from a CMS so there isn’t a way to hardcode it somewhere nice.

Advertisement

Answer

There is a head method (Docs) which will let you to load external scripts but I can’t find the documentation for the script property.

I would dynamically load the script only on the client side like this:

<template>
  <div id="knack-dist_6">Loading...</div>
</template>

<script>
export default {
  // ...
  async created() {
    // Do not load the script on the server side
    if (!process.client) return
   
    // Function to load the external script
    function loadLib(id, distKey) {
      const scriptId = 'knack-js'

      return new Promise((resolve, reject) => {
        // If script already exists than do not load it again
        if (document.getElementById(scriptId)) {
          resolve()
          return
        }

        const s = document.createElement('script')

        s.src = `https://loader.knack.com/${id}/${distKey}/knack.js`
        s.id = scriptId
        s.type = 'text/javascript'

        s.onload = () => {
          resolve()
        }

        s.onerror = (e) => {
          reject(e)
        }

        document.head.appendChild(s)
      })
    }

    try {
     if (!window.app_id) {
        window.app_id = 'ID_HERE'
        window.distribution_key = 'dist_6'
     }

      await loadLib('ID_HERE', 'dist_6')
    } catch (e) {
      // Handle script loading error
      console.error(e)
    }
  }
}
</script>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement