Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
Running an external JS script only if key in localStorage is present

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.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda