Friday, 14 July, 2017 UTC


Summary

Web developers still have a difficult job when it comes to mobile; the web will never provide as many APIs or as much control as native mobile platforms but our users expect the same excellent experience.  Creating HTML5 games and media-heavy apps for the web can be really difficult, as you really have to pay attention to performance the the rest of the little things that native platforms provide.
One of those small features includes preventing the device from sleeping when the user hasn’t been active.  Imagine your user playing a game that doesn’t require much interaction, experiencing a VR demo, or even just a blog post or slideshow, and the screen suddenly goes black — that’s an annoyance that your users may not (and shouldn’t have to) tolerate.  That’s where NoSleep.js comes in: a small Wake Lock API shim to prevent the browser and device from going to sleep!
Using NoSleep.js is super easy.  To start the no sleep effect, simply add:
var noSleep = new NoSleep();

function enableNoSleep() {
  noSleep.enable();
  document.removeEventListener('touchstart', enableNoSleep, false);
}

// Enable wake lock.
// (must be wrapped in a user input event handler e.g. a mouse or touch handler)
document.addEventListener('touchstart', enableNoSleep, false);
Once you want to cede control of sleep, simply call the disable method:
// Disable wake lock at some point in the future.
// (does not need to be wrapped in any user input event handler)
noSleep.disable();
So how does NoSleep.js prevent the sleep effect?  NoSleep.js mocks a tiny mp4 video and continuously plays it, which works because browsers know enough to not signal sleep when a video is playing.  What a clever way to prevent the device from sleeping!
Will we ever get a JavaScript API that allows us to control whether the device sleeps or  not?  Possibly — no browser vendor has committed to the Wake Lock API yet.  That’s why us web developers have to stay clever and take matters into our own hands!
The post Prevent Mobile Browser From Sleeping appeared first on David Walsh Blog.