I need to conditionally run the following script. But the problem is that even if the script tag appears, the script itself doesn't work:
<script defer data-domain="currentsite.com" src="https://metrics.myplausibleserver.com/js/plausible.js"></script>
The condition would be to not have this key in localStorage: "plausible" = false*
(*): actually it doesn't matter if it's true or false. I just need the key to exist.
The script is a Plausible snippet (web traffic metrics).
So I'm using this at the end of the body tag:
<script type="text/javascript" src="/js/plausibleSwitch.js"></script>
Which contains:
const plausibleSnippet = '<script defer data-domain="currentsite.com" src="https://metrics.myplausibleserver.com/js/plausible.js"></script>';
if (localStorage.getItem('plausible') == null) {
document.getElementsByTagName("head")[0].innerHTML += plausibleSnippet;
}
If I have the key in the localStorage, the script doesn't appear (which is fine). But if I don't have it, the script appears, but it doesn't work at all (the Plausible dashboard doesn't register any visit to the website).
Needless to say, if I place the script directly in the head tag (without using the JS code), it works.