I have a script on a page:
JavaScript
x
2
1
<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>
2
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:
JavaScript
1
55
55
1
<template>
2
<div id="knack-dist_6">Loading</div>
3
</template>
4
5
<script>
6
export default {
7
// ...
8
async created() {
9
// Do not load the script on the server side
10
if (!process.client) return
11
12
// Function to load the external script
13
function loadLib(id, distKey) {
14
const scriptId = 'knack-js'
15
16
return new Promise((resolve, reject) => {
17
// If script already exists than do not load it again
18
if (document.getElementById(scriptId)) {
19
resolve()
20
return
21
}
22
23
const s = document.createElement('script')
24
25
s.src = `https://loader.knack.com/${id}/${distKey}/knack.js`
26
s.id = scriptId
27
s.type = 'text/javascript'
28
29
s.onload = () => {
30
resolve()
31
}
32
33
s.onerror = (e) => {
34
reject(e)
35
}
36
37
document.head.appendChild(s)
38
})
39
}
40
41
try {
42
if (!window.app_id) {
43
window.app_id = 'ID_HERE'
44
window.distribution_key = 'dist_6'
45
}
46
47
await loadLib('ID_HERE', 'dist_6')
48
} catch (e) {
49
// Handle script loading error
50
console.error(e)
51
}
52
}
53
}
54
</script>
55