Practical Drupal Development #2 How to add CSS or JavaScript files to a Drupal theme conditionally

Drupal

We continue with this series intended for posing practical issues to be solved by using all those development tools provided by Drupal (themes, modules, API...).

Issue to be solved

This time I'll be covering a personal issue related to CSS and JavaScript files responsible for my Google Plus block to work properly. The point is that every single CSS/JavaScript files related to this block is added to the theme regardless of whether or not the block is present on the page. This is because I added them to the theme by using its .info file. By the way, this block is located on the homepage of this site.. Although this behaviour does not entail a serious loss of performance, there's no need to add them to all pages since the block is present on the front page only.

template_preprocess_page, drupal_add_css and drupal_add_js

In order to perform this new task, I'm going to use the template_preprocess_page function along with the drupal_add_css and drupal_add_js functions.

Unlike Drupal 6, Drupal 7 delays the creation of CSS/JavaScript lists until the template_ process_html function is run. That's why you're able to call drupal_add_css or drupal_add_js in a module/template_preprocess_function. Prior to Drupal 7, these lists of files were already generated before any of the preprocess functions were run.

/**
 * This preprocess function is the primary processor for theme hook page.
 */
function cti_flex_preprocess_page(&$variables) {

  $front_page = drupal_is_front_page();

  $path = drupal_get_path('theme', 'cti_flex');

  if ($front_page) {

    $options = array(

      'type' => 'file',

      'group' => CSS_THEME,

      'every_page' => false,

      'media' => 'all',

      'preprocess' => false,

    );

    drupal_add_css($path . '/css/activities.css', $options);

    drupal_add_css($path . '/css/more-button.css', $options);

    drupal_add_css($path . '/css/ajax-loader.css', $options);

    $options = array(

      'type' => 'file',

      'scope' => 'header',

      'group' => JS_THEME,

      'every_page' => false,

      'cache' => true,

      'preprocess' => false,

    );

    drupal_add_js($path . '/js/rfc3339date/rfc3339date.js', $options);

    drupal_add_js($path . '/js/googleplus/activities.js', $options);

  }

}

The file to be edited in order for you to add this piece of code is named template.php, which is analogous to a module's .module file. Do not forget to remove or comment those lines related to these CSS/JavaScript files in the .info file.

For further information about drupal_add_css and drupal_add_js functions: drupal_add_css - drupal_add_js.