4elements, web design and consultancy

  1. HTML5 Page Visibility API

    In earlier days, we had browsers that did not feature tabbed browsing, but today when you look at all browsers available, we can see that all browsers offer that. Being a programmer, I normally have 10-15 tabs open at a time, sometime this numbers goes above 25-30.

    Why This API?

    Earlier, it was not possible to determine which tab is active and which was not, but with the help of the HTML5 Visibility API, we can detect whether our visitor is looking at our web page or not. 

    In this tutorial we will understand how to deal with HTML5 Visibility API and one simple demo to discover the status of the our page. In this demo we will alter the document title based on Status of Page Visibility.

    Checking Visibility Status of Page

    With the launching of this API we have welcomed two new document property which does two different functions. The first one is document.visibilityState and second one is document.hidden.

    document.visibilityState holds four different values which are as below:

    • hidden: Page is not visible on any screen
    • prerender: Page is loaded off-screen and not visible to user
    • visible: Page is visible
    • unloaded: Page is about to unload (user is navigating away from current page)

    document.hidden is boolean property, that is set to false if page is visible and true if page is hidden.

    Now we can control how our websites will behave when our website is hidden to user.

    Right away we know about our availability properties, but now it's time to listen to the event so that we can be notified about the new condition of the page visibility. This is done via the  visibilitychange event. We will see a quick demo on how to deal with this event.

    document.addEventListener('visibilitychange', function(event) {
      if (!document.hidden) {
        // The page is visible.
      } else {
       // The page is hidden. 
      }
    });

    This code is simply a basic instance of utilizing this event and discover the current status of webpage. But to let you know that both these properties and method should be used vendor prefixed, because these events and properties are vendor-prefixed in some of the browsers. Now we will see the same code in a cross browser manner:

    // Get Browser-Specifc Prefix
    function getBrowserPrefix() {
      
      // Check for the unprefixed property.
      if ('hidden' in document) {
        return null;
      }
    
      // All the possible prefixes.
      var browserPrefixes = ['moz', 'ms', 'o', 'webkit'];
    
      for (var i = 0; i < browserPrefixes.length; i++) {
        var prefix = browserPrefixes + 'Hidden';
        if (prefix in document) {
          return browserPrefixes;
        }
      }
    
      // The API is not supported in browser.
      return null;
    }
    
    // Get Browser Specific Hidden Property
    function hiddenProperty(prefix) {
      if (prefix) {
        return prefix + 'Hidden';
      } else {
        return 'hidden';
      }
    }
    
    // Get Browser Specific Visibility State
    function visibilityState(prefix) {
      if (prefix) {
        return prefix + 'VisibilityState';
      } else {
        return 'visibilityState';
      }
    }
    
    // Get Browser Specific Event
    function visibilityEvent(prefix) {
      if (prefix) {
        return prefix + 'visibilitychange';
      } else {
        return 'visibilitychange';
      }
    }
    
    

    We have all browser prefixed properties and event is ready to apply. Now we will change our previous code accordingly.

    // Get Browser Prefix
    var prefix = getBrowserPrefix();
    var hidden = hiddenProperty(prefix);
    var visibilityState = visibilityState(prefix);
    var visibilityEvent = visibilityEvent(prefix);
    
    document.addEventListener(visibilityEvent, function(event) {
      if (!document[hidden]) {
        // The page is visible.
      } else {
       // The page is hidden. 
      }
    });

    Where Can We Use This API?

    There are a number of different scenarios where we can consider using this API.

    1. Imagine you are on the dashboard the page and page is polling details from some RSS feed or API on regular interval say two minutes. So we can restrict call to the RSS feed or API if page is not visible to the user (i.e., the user is not actually looking at page).
    2. For and image slider. we can limit movement of slider images when page is hidden.
    3. In a similar manner, we can show HTML Notification only when page is hidden to the user.

    Up to here we have seen code to use HTML5 Page Visibility API, it's time for some action right away.

    Demonstration

    • Demo 1: This demonstration presents the use of Page Visibility API to change Page Title. View Demo
    • Demo 2: This demo demonstrates how we can restrict polling data from the server when page is inactive. 

    In this demo, we will examine how we can restrict polling the server for fresh information, but only when the user is looking at the page. I am assuming that jQuery is already included in your page. Here we will increase only the count, but this can be replaced with real server polling instead.

    The HTML

    <!-- This element will show updated count -->
    <h1 id="valueContainer">0</h1>

    The JavaScript

    <script type="text/javascript">
        
    	// Get Browser Prefix
    	var prefix = getBrowserPrefix();
    	var hidden = hiddenProperty(prefix);
    	var visibilityState = visibilityState(prefix);
    	var visibilityEvent = visibilityEvent(prefix);
    	
    	var timer = null;
    	
    	function increaseVal() {
    		var newVal = parseInt($('#valueContainer').text()) + parseInt(1);
    		$('#valueContainer').text(newVal);
    		document.title = newVal + ': Running'; 
    		
    		timer = setTimeout(function() {
    			increaseVal();
            }, 1);
    	}
    	
    	// Visibility Change 
    	document.addEventListener(visibilityEvent, function(event) {
    		  if (document[hidden]) {
    			  clearTimeout(timer);
    			  var val = parseInt($('#valueContainer').text());
    			  document.title = val + ': Pause'; 
    		  } else {
    			  increaseVal();  
    		  }
    	});
    	
    	increaseVal();
    	
    </script>

    View Demo

    Browser Support

    If you wan to look at browser support for for this API, then I would advise looking at Can I use?. But to programmatically find out for the browser support I would suggest taking this article to Detect Support for Various HTML5 Features. So far we have really good support for this API in almost all major and latest browsers.

    Conclusion

    I would say that we have had a very good API which included only two properties and just one event. This way, it can be easily integrated with your existing application which may positively affect your user experience. Ultimately, now we can control how our websites will behave when our website is hidden to user.

     

    0 Comments

    Leave a comment › Posted in: Daily

0 Comments

Got anything to add?

(Basic HTML is fine)