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.

Advertisements

Options for Building a Website from a Developers Perspective

Over the years I’ve built many different types of websites. These range from being a few pages, to being very customized with advanced features. I’ve learned there is no clear definition in the best way to create a website. But I do think there are advantages and disadvantages to pursuing different methods. This article takes an analytical look at each option. Continue reading

Drupal 8: A Look Ahead

Since the release of Drupal 7, there has been much talk about what to expect for the next major release of Drupal. Drupal’s founder Dries Buytaert has outlined some of the goals for Drupal 8. These goals provide some insights into what we are likely to see in the next Drupal version. Continue reading

PHP Content Management System of Choice

Guest author Carrie Donalds goes through her perspective on WordPress, while I give you my take on this subject. There are many PHP content management systems out there, and we go through a few different perspectives.

If you want to write a guest post on a specific PHP or project management related topic, please contact me. Continue reading