'Hotjar on site that uses turbolinks?
I implemented hotjar as instructed (i.e. copy paste the code below into the page <head>) but the hotjar javascript only appears on the first page visit to the site because it's in the <head> and that means it's only loaded once when turbolinks are on.
Is there any way to leave turbolinks on but have the hotjar script function as expected?
I can see some discussion but no clear resolution
For reference:
<script>
(function(h,o,t,j,a,r){
h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
h._hjSettings={hjid:2019490,hjsv:6};
a=o.getElementsByTagName('head')[0];
r=o.createElement('script');r.async=1;
r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
a.appendChild(r);
})(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
</script>
Solution 1:[1]
I believe you could do something like this
<script>
document.addEventListener("turbolinks:load", function(event) {
(function(h,o,t,j,a,r){
h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
h._hjSettings={hjid:2019490,hjsv:6};
a=o.getElementsByTagName('head')[0];
r=o.createElement('script');r.async=1;
r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
a.appendChild(r);
})(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
})
</script>
to trigger the code on every page load
Solution 2:[2]
Had a similar issue using the newer "turbo" library.
Forcing the injected script tag to have a data-turbo-track="reload" attribute seems to work:
<script>
(function(h,o,t,j,a,r){
h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
h._hjSettings={hjid:123456,hjsv:6};
a=o.getElementsByTagName('head')[0];
r=o.createElement('script');r.async=1;
// this seems to do the trick
r.setAttribute("data-turbo-track","reload")
r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
a.appendChild(r);
})(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | FDI |
| Solution 2 | Sven Tantau |
