I need to conditionally add css to a page based on the page content / URL. In the past (D6 and down) I was always advised against using hook_init() mostly because of it's weird load order in the Drupal bootstrap process. It was not uncommon to see the hook fire multiple times on a each page load - this still might be the case.
Looking at the D7 docs for hook_init() the following code example is provided:
function hook_init() {
// Since this file should only be loaded on the front page, it cannot be
// declared in the info file.
if (drupal_is_front_page()) {
drupal_add_css(drupal_get_path('module', 'foo') . '/foo.css');
}
}
The example implies that conditional addition of css makes sense while:
To add CSS or JS that should be present on all pages, modules should not implement this hook, but declare these files in their .info file.
using a modules .info for site wide css additions.
Questions:
What are the options in adding css via drupal_add_css conditionally besides hook_init?
Has anyone had luck using the theme hook -> hook_html_head_alter():
THEME_NAME_html_head_alter(&$head_elements) {
if (drupal_is_front_page()) { drupal_add_css(drupal_get_path('module', 'foo') . '/foo.css'); }
}
or use the theme engine for the theme hook:
phptemplate_html_head_alter(&$head_elements)