Drupal 7 Conditionally Add JavaScript or CSS Based on Node Type

Oftentimes features are specific to node types. The following code added to your theme's template.php will allow you to only include JavaScript when displaying a specific node type.

This code is including an external JavaScript file in the page header, but you can adjust the drupal_add_js arguments to include inline JavaScript or cause the JavaScript to be added at the bottom of a page.

function mytheme_preprocess_page(&$vars) {
  if (isset(
$vars['node'])) {
    if (
$vars['node']->type == 'mynodetype') {
drupal_add_js(drupal_get_path('theme', 'mytheme') . '/js/scripts.js', array('type' => 'file', 'scope' => 'header', 'weight' => 1));

Be sure to update the function replacing "mytheme" and "mynodetype" accordingly and flush cache.

This same code can be used for CSS by using drupal_add_css instead of drupal_add_js.


Add new comment