Call Function Simultaneously With Location.reload To Display A Proper Message In Javascript
Solution 1:
If you have to literally reload the existing page (rather than switching to an ajax call, etc.), you can't do the "reloading" message in-page. What you can do is open a child window with a name:
var wnd = window.open("reloading.html", "reloading", "width=400,height=400,toolbar=no);
sessionStorage.setItem("reloading", "Yes");
Note the session storage flag so we know whether we've done that. Then in the startup code for the page you're reloading, close that window:
if (sessionStorage.getItem("reloading")) {
sessionStorage.removeItem("reloading");
var wnd = window.open("", "reloading");
if (wnd) {
wnd.close();
}
}
That looks strange, but calling window.open
with a ""
URL and the same name as an open window your page origin has access to returns a reference to the existing window, which you can close.
The flag is important because otherwise, the window.open
tries to open a new window, which will almost certainly trigger the popup blocker in your browser.
Here's a complete, working example (doesn't work correctly in a jsFiddle or Stack Snippet, those are sandboxed environments in various ways):
<!DOCTYPE HTML"http://www.w3.org/TR/html4/strict.dtd"><html><head><metacharset="UTF-8"><title>Reloading Window Example</title><style>body {
font-family: sans-serif;
}
</style></head><body><inputtype="button"value="Reload"><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><script>if (sessionStorage.getItem("reloading")) {
sessionStorage.removeItem("reloading");
var wnd = window.open("", "reloading", "height=400,width=400,toolbar=no");
if (wnd) {
wnd.close();
}
}
$("input").on("click", function() {
var wnd = window.open("", "reloading", "height=400,width=400,toolbar=no");
wnd.document.write("<!doctype html><head><title>Reloading</title></head><body>Reloading...</body></html>");
setTimeout(function() {
sessionStorage.setItem("reloading", "Yes");
location.reload();
}, 2000);
});
</script></body></html>
Solution 2:
Depends what's changing after page reload, but if you're showing "loading" message, you should be loading something in the meantime.
For that purpose use ajax (as you're using jquery): http://api.jquery.com/jquery.ajax/
Load a result, a portion of a page or a whole new page and replace whatever needs replacing on success callback.
Post a Comment for "Call Function Simultaneously With Location.reload To Display A Proper Message In Javascript"