Take the 2-minute tour ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

So I'm working on a site where the ability to add custom javascript is core to the site's functionality. Right now, I'm using the Code Per Node module to handle this, but I have a feeling it's going to be a bit unwieldy when I'm dealing with 20 or 30 pages with custom javascript. Also, I'd love to have a way to keep the js in source control, not the database.

In my mind, the idea solution would be able to either upload or reference an existing javascript file to be loaded in a script block at the bottom of the page. Or, alternatively, pay close attention to how I'm calling things on the DOM and just have all of javascript files minified into one that would be called by my theme's .info file.

Is there a better alternate approach to this problem?

share|improve this question
add comment

2 Answers

I had a theme, called bikeswitzerland. There I had a file template.php, where I added the following code:

function bikeswitzerland_preprocess_page($vars)
{
       $nid = array_keys($vars["page"]["content"]["system_main"]["nodes"]);
       $nid = $nid[0];

       $alias = drupal_get_path_alias("node/" . $nid);
       $theme_path = drupal_get_path('theme', 'bikeswitzerland');

       switch($alias)
       {
       case 'ask-us':
              drupal_add_css($theme_path . "/css/ask_us.css");
              break;
       };
}

Use preprocess_page hook in your theme. Upload your css files into a dir and create a table in the database, that stores the mapping between the page aliases/urls and appropriate css files.

Then inside the function check, what is the current page url and attach the appropriate css, like I did. And you'll solve your problem.

share|improve this answer
    
Yeah, this is one option I'm looking into. Thanks for sharing this code. My main issue is JS, so I might just create on big javascript library and have CPN call functions for it. –  CamelBlues Feb 20 '13 at 20:08
add comment

I have found the bellow article that may be help you to add custom js and css to a specific page in Drupal. Take a look, maybe it may help you: http://wearepropeople.com/blog/7-ways-to-add-custom-js-and-css-to-a-page-in-drupal

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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