The application I'm developing is built around jQuery Mobile and some Ajax to refresh parts of the page. Like sites that use automatic refresh, I want to stop the refresh after some condition (time/visibility/etc.) so my server isn't bombarded with unneeded requests. The application has a status screen that is commonly checked by the user, and ideally my scripts would know that the browser window has come into focus and it would be a good time to refresh. I've done this before in desktop webapps, but I'm noticing a lot of variation on the mobile side between different platforms and browsers, for example:
The best I've been able to do so far is a set of heuristics that look at available events + when there was detected user interaction with the page, but it's clunky and results in cases where the user jumps back to the page and has to manually refresh. Not great.
Any clever techniques for solving this?
If you just want to know if browser window has been out of focus, use the requestAnimationFrame function.
window.requestAnimFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
<add browsers here>
Then in your code
var lastupdate = new Date()
(function loop() {
var now = new Date();
if ( now - lastupdate > <some treshold like 1 second> ) {
// browser was suspended and did come back to focus
}
lastupdate = now;
window.requestAnimFrame(loop);
})();
Trick is, that browsers do not give animation frame if tab or window is out of focus. Normal setInterval and setTimeouts will still work. This loop will run continously when window is on focus, but overhead is minimal, it's called maybe 3-5 times per second in mobile devices.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With