Search code examples
javascripthtmlonclickonclicklistenerreload

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?


Solution

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