2

I am using drupal_add_css() and drupal_add_js() to add CSS and JavaScript files to my Drupal site. I am doing this in a module called control so the function I'm using is called control_preprocess_page(&$vars).

But in my theme nothing is added!

1
  • can you add some sample code? Commented Dec 13, 2010 at 21:22

3 Answers 3

5

The reason these functions aren't working within the preprocess_page() function is that template_preprocess_page() (which is called first) has already formatted the structured content into variables $scripts and $styles. If you want to add additional js or css at the preprocess level, you need to regenerate those 2 variables, something like this:

function control_preprocess_page(&$vars) {
  // Add new CSS.
  drupal_add_css('path/to/css/foo.css');
  // Rebuild the 'styles variable.
  $vars['styles'] = drupal_get_css();

  // Add new JS.
  drupal_add_js(...);
  $vars['scripts'] = drupal_get_js();
}

Using drupal_add_js/drupal_add_css in hook_init, or a more precisely targeted function (eg, an alter hook, or nodeapi hook, if applicable), will avoid having to regenerate those variables.

Sign up to request clarification or add additional context in comments.

Comments

4

At the point your CSS/JS is needed, you can call it with drupal_add_css/js. You can also use it in the hook_init(), if your module is used on every page.

1 Comment

+1: the init hook is useful to globally include JS/CSS. You can also include upon node loading (in hook_nodeapi), comment altering, form altering, and others.
0

Some pointers that might help:

1) Place your CSS/JS script in your theme folder. 2) In your node.tpl.php file use the following:

<?php drupal_add_js(drupal_get_path('theme', 'INSERT_NAME_OF_THEME') . '/INSERT_NAME_OF_CSS_FILE.css'); ?>

3) If you place your CSS in a sub folder, you will need the following code:

4) Refresh the cache at yousite.com/admin/settings/performance

5) Sometimes I find that I have to disable the theme at admin/build/themes and the re-enable it.

1 Comment

While you could do this, it isn't best practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.