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

183
Visualizações
javascript location.reload doesn't reload the page in a wrong way

I'm trying to refresh a page every time a user click the button so the page is set back to source code. but the location.reload() is executed after the code, and not at the beginning.

btn.addEventListener("click", () => {
      location.reload()
      //code...
}

Why does not reload the page immediately when the button is clicked, but only when the function ended?

Is there another way to set the page back to the source code?

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

why does not reload the page immediately when the button is clicked but only when the function ended?

Because JavaScript blocks navigation.

If it didn't, then the page would reload and the rest of the function wouldn't run at all (because the page it was running in has been destroyed and a new version loaded instead).

If you want to cause the page to reload and then a function to run on the new page, then you need to pass the instruction to run that function to the newly reloaded page (e.g. via sessionStorage).

When the page loads (e.g. wait for a DOMContentLoaded event), check for the instruction, act on it if needed, then delete the instruction so it won't trigger automatically next time the page loads from another mechanism).

about 4 years ago · Santiago Gelvez Relatório

0

This here seems to work but you would have to implement it in a way so that btnClicked is not always true to execute the other code. Wrapping it around the if to check 'true'. Then it reloads the page without going to the else. Setting the btnClicked to false will run the else code without reloading the page.

Hopefully this can give you an idea!

<!DOCTYPE html>
<html>
<body>

<button class="btn" >Click to reload page</button>
<p class="text">Original Text</p>

<script>
const btn = document.querySelector('.btn');
const text = document.querySelector('.text');

btn.addEventListener("click", () => {
var btnClicked = true
    if(btnClicked == true){
      location.reload()
    } else {
      text.innerHTML = 'New Text';
    }
})

</script>
</body>
</html>

about 4 years ago · Santiago Gelvez Relatório
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