It seems that I must be missing something completely elementary. What I’m trying to achieve looks like quite a common case, and so it makes me wonder why there is no straightforward way.
The problem is that I would like to refresh the current page from JavaScript and simultaneously land on a #section. If I do simply:
document.location.href = document.location.href + "#section";
all browsers I tested just scroll to that #section (no reload). It makes sense in a way. Just for completeness, if I do
document.location.assign(document.location.href + "#section");
it does the same thing (not surprisingly; it boils down internally to the same function for sure). Finally, the document
object seems to have also the document.reload()
function which takes an optional boolean argument specifying whether I want to force the reload, but obviously, it does not allow to specify the #section. The only way I could find (using these methods) was the following combination:
document.location.assign(document.location.href + "#section");
document.location.reload();
But it is not ideal, because as you have probably guessed, it scrolls and then reloads which causes the browser to actually scroll three times in the end.
I know that there are ways around it: server side redirect or adding some unique random query string parameter, but it seems strange that there is no simple way.