Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!