I made a custom js script for a little calculator. I want to use this in only 1 node (article or page) so I do not want to load it via tpl files etc because I do not need it sitewide. And also: if every custom script (that I use only in 1 node) has to be loaded sitewide I would get an immense head section after some time. Does anyone have experience with how to do this in a simple and safe way?

Thanks. Frank


4 Answers 4


In the template.php you will write this small piece of code:

function MYTHEME_preprocess_node($vars) {
 if (drupal_get_path_alias("node/{$vars['#node']->nid}") == 'yournid') {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . "/script/js");

Replace foo with values related to your need.


code for adding JS to particular path:

if ($_SERVER['REQUEST_URI'] == '/path/to/node') {

to attach js to node:

function my_module_node_view($node, $viewmode, $langcode) {
  $node->content['#attached']['js'][] = array('type' => 'file','data' => drupal_get_path('module', 'my_module') . '/my_script.js',);



Another option is JS Injector. Though I haven't used this module. This requires no programming as it provides user interface to administrators.


you need to use php filter or need to create tpl file for single node to accomplish this. With php filter or tpl you need to put only this code.

  drupal_add_js('jQuery(document).ready(function () {
  });', 'inline');
  • PHP filter is highly discouraged.
    – Brady
    Aug 28, 2015 at 11:44
  • I understand it creates a potential security risk especially in the hands of end users or people new to Drupal or PHP.
    – vgoradiya
    Aug 28, 2015 at 11:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.