Home > front end >  javascript location.reload doesn't reload the page in a wrong way
javascript location.reload doesn't reload the page in a wrong way

Time:07-18

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?

CodePudding user response:

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).

CodePudding user response:

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  >Click to reload page</button>
<p >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>

  • Related