Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

186
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda