In working on the new Pantone Moods this week, I needed to add a listener to the widget to halt the realtime updates if a user no longer had the page active (meaning, they switched to another browser tab or application) to prevent unnecessary traffic to the server.
The application cycles through the ten most recent Moods posts and, upon nearing the end of its cache, queried the server for a new supply. However, if someone’s focus wasn’t on the page, it makes no sense to keep collecting and displaying results.
With ActionScript 3, this task is quite easy:
stage.addEventListener(Event.DEACTIVATE, onDeactivate); stage.addEventListener(Event.ACTIVATE, onActivate); |
And it’s just as easy when programming for Mobile Applications:
NativeApplication.nativeApplication.addEventListener(Event.ACTIVATE, onActivate); NativeApplication.nativeApplication.addEventListener(Event.DEACTIVATE, onDeactivate); |
With JQuery, we can now accomplish the same thing for AJAX/PHP browser applications to no longer commit resources to updating a page that isn’t being viewed:
$(function(){ $(window).bind('blur', function(){ onDeactivate(); }); $(window).bind('focus', function(){ onActivate(); }); // IE EVENTS $(document).bind('focusout', function(){ onDeactivate(); }); $(document).bind('focusin', function(){ onActivate(); }); }); |
Note that the second two methods must be added because Internet Explorer uses focusin/focusout rather than simply focus/blur.