Community Documentation

Modernizr.load() and Drupal: Basics

Last updated February 11, 2013. Created by rupl on February 11, 2013.
Log in to edit this page.

Modernizr can also be a conditional resource loader, which means it can load different CSS or JS files based on the outcome of Modernizr tests. This capability is only present when you have selected Modernizr.load on the download builder.

Once you have Modernizr.load() available, the Modernizr module offers multiple ways to create Modernizr.load() commands. No matter how you create them, the Modernizr.load objects will all print out on your page in the exact spot they should be, coming after the Modernizr <script> tag but before most of the page markup, meaning they begin to be fetched as soon as possible.

The Modernizr module collects calls to this API from three places:

From within a theme's .info file

For people most familiar with theming, adding lines to an .info file might be the most comfortable method. It is easier to understand conditional loading if you consider that it already happens in every .info file you already create:

stylesheets[all][] = my/styles.css

This stylesheet declaration contains the word all, which defines the media attribute when the stylesheet is printed. You could easily change the output to be something like this:

stylesheets[screen and (min-width: 960px)][] = my/desktop.css

And now the condition is much less permissive than "all." In much the same way, the Modernizr module can accept instructions for Modernizr.load() commands using a similar syntax:

modernizr[Modernizr.boxshadow][yep][] = css/boxshadow.css
modernizr[Modernizr.boxshadow][nope][] = css/no-boxshadow.css

...becomes...

Modernizr.load({
  'test' => Modernizr.boxshadow,
   'yep' => 'css/boxshadow.css',
  'nope' => 'css/no-boxshadow.css'
});

hook_modernizr_load()

Modules can implement a hook to create Modernizr.load() commands:

<?php
/**
* Implements hook_modernizr_load().
*/
function MYMODULE_modernizr_load(&$load) {
 
$load[] = array(
   
'test' => 'Modernizr.boxshadow',
    
'yep' => array('css/boxshadow.css'),
   
'nope' => array('css/no-boxshadow.css'),
  );
  return
$load;
}
?>

...becomes the exact same Modernizr.load() command printed above.

hook_modernizr_load_alter() (for template.php)

Using a hook inside template.php is identical to using a module hook. The minor difference is that themes cannot use regular hooks, and can only implement "alter" hooks. Modernizr module includes drupal_alter() hooks for both of its APIs, meaning template.php has access to the same options as modules:

<?php
/**
* Implements hook_modernizr_load_alter().
*/
function MYTHEME_modernizr_load_alter(&$load) {
 
$load[] = array(
   
'test' => 'Modernizr.boxshadow',
    
'yep' => array('css/boxshadow.css'),
   
'nope' => array('css/no-boxshadow.css'),
  );
  return
$load;
}
?>
nobody click here