James is a technologist, executive & entrepreneur, working in the arena of the mobile web, all while living around the world. This year he happens to be living on an island off Belize.

He also wrote modernizr-server – a way to bring Modernizr browser data to your server scripting environment. PHP is currently supported, and James intends to offer other server-side environments in the future, but that’s going to be based on demand!

We’ve covered Modernizr being used in other projects before. Modernizr is a great way to find out about your user’s browser capabilities. However, you can only access its API on the browser itself, which means you can’t easily benefit from knowing about browser capabilities in your server logic.

Progressive enhancement, media queries and body classes are fine for tweaking sites and their appearance. But for structural changes to sites and pages, sometimes it’s much simpler to just emit the right markup from the server in the first place.

The modernizr-server library is a way to bring Modernizr browser data to your server scripting environment. For example, in PHP:

<?php

    include('modernizr-server.php');

    print 'The server knows:';
    foreach($modernizr as $feature=>$value) {
        print "<br/> $feature: "; print_r($value);
    }

?>

The server knows:
canvas: 1
canvastext: 1
geolocation: 1
crosswindowmessaging: 1
websqldatabase: 1
indexeddb: 0
hashchange: 1
...

How it works

The first time the user accesses a page which includes the modernizr-server.php library, the library sends the Modernizr script to the client, with a small script added to the end. Modernizr runs as usual and populates the feature test results.

The small suffix script then serializes the results into a concise cookie, which is set on the client using Javascript. It then refreshes the page immediately.

This second time the PHP script is executed, the library takes the cookie and instantiates the server-side $modernizr object with its contents. If possible, this is placed in the PHP $_SESSION so that it can be quickly accessed in subsequent requests.

While either of the cookie or session remain active, no further execution of the Modernizr script will take place. If they both expire, the next request to a page containing modernizr-server.php will cause the browser to rerun the Modernizr tests again.

And also …

You might also want to read James’ blog post on Modernizr on the server-side.

Check out the codes

[Source on GitHub] & [Documentation]


Have comments? Send a tweet to @TheChangelog on Twitter.

Subscribe to The Changelog Weekly – our weekly email covering everything that hits our open source radar.