Correct Way in Adding JS/CSS to a Block in Drupal 7

In Drupal, drupal_add_js() and drupal_add_css() are great functions for adding JS/CSS to the module or theme layer. However, if you do this inside of the ‘#markup’ call in Drupal 7, you are doing it wrong.

This becomes obvious when you turn block caching or anonymous page caching on, because the JS/CSS won’t be included on the page. Here is the code in how to do it correctly.

/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks['testblock'] = array(
    'info' => t('Testing Block'),
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function mymodule_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'testblock':
      $block['subject'] = t('Testing block');
      $block['content'] = array(
        '#markup' => mymodule_testblock_content(),
        '#attached' => array(
          'css' => array(
            drupal_get_path('module', 'mymodule') . '/css/mymodule.css',
          ),
          'js' => array(
            drupal_get_path('module', 'mymodule') . '/js/mymodule.js',
          ),
        ),
      );
      break;
  }
  return $block;
}

function mymodule_testblock_content() {
  return '<p>This is a testing block!</p>';
}

This code will ultimately call drupal_add_js() and drupal_add_css(), but it is hit even with block caching on. It makes sense when you think about it, because block caching grabs the html generated in ‘#markup’ once, and doesn’t call it again when it is cached.

Here is a great article that goes through another example in how to do this.