Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include CSS or Javascript file for specific node in Drupal 6

Tags:

What is the best method for including a CSS or Javascript file for a specific node in Drupal 6.

I want to create a page on my site that has a little javascript application running, so the CSS and javascript is specific to that page and would not want to be included in other page loads at all.

like image 605
Evan Avatar asked Sep 14 '08 23:09

Evan


People also ask

How add JS file to Drupal?

The Drupal API function drupal_add_js() lets you add a JavaScript file, setting or inline code to the page and it takes 5 parameters (see the api reference). The first parameter is always going to be a path to a js file, an array, or a piece of JavaScript code.

Does Drupal support JavaScript?

Since Drupal 8, the available JavaScript files, which were referenced in . info files in Drupal 7, are now referenced in . yml files. Also, stylesheets (CSS) and JavaScript (JS) are loaded through the same system as modules (code) and themes: asset libraries.


1 Answers

I'd advise against using hook_nodeapi for that. Adding CSS and Javascript is related to layout so hook_nodeapi is not the place for it: use themeing. This way, you can override those files when you're going to develop a new theme. Doing that with the nodeapi approach would be a bit harder (you'd have to search the js/css list for the files, remove them and replace them with your own).

Anyway: what you need to do is add a node preprocess function that adds those files for you. You can do this either in a module or in a custom theme. For a module this would be:

function mymodule_preprocess_node(&$variables) {   $node = $variables['node'];   if (!empty($node) && $node->nid == $the_specific_node_id) {     drupal_add_js(drupal_get_path('module', 'mymodule') . "/file.js", "module");     drupal_add_css(drupal_get_path('module', 'mymodule') . "/file.css", "module");   } } 

or for a theme:

function mytheme_preprocess_node(&$variables) {   $node = $variables['node'];   if (!empty($node) && $node->nid == $the_specific_node_id) {     drupal_add_js(path_to_theme() . "/file.js", "theme");     drupal_add_css(path_to_theme(). "/file.css", "theme");   } } 

Don't forget to clear the cache, first.

These functions are called before the node is themed. Specifing the js/css there allows for a cascaded approach: you can have the generic/basic stuff in the module and provide enhanced or specific functionality in the theme.

like image 101
Inferis Avatar answered Sep 18 '22 06:09

Inferis