20

Is it possible to add external javascripts directly into the .info file of a theme?
e.g scripts[] = http://cdn.jquerytools.org/1.2.6/jquery.tools.min.js

  • Are you just seeking to add the CDN version of jQuery Tools to your theme, or are you explicitly asking whether can be done from a theme's .info file? – mpdonadio Jan 9 '12 at 21:17
  • It is explicitly to add external javascript to the .info file – JurgenR Jan 10 '12 at 7:38
  • So you wanted to add it to the .info file and you accepted an answer that doesn't talk about the .info file at all and shows the drupal_add_js method? – mpdonadio Jan 10 '12 at 11:49
  • Yes if it doesn't work in the info file I'm glad with the best possible solution. – JurgenR Jan 10 '12 at 12:55
24

In your theme's template.php file use drupal_add_js() to the page preprocess method (or an equivalent preprocess).

function hook_preprocess_page(&$vars) {
  drupal_add_js('http://cdn.jquerytools.org/1.2.6/jquery.tools.min.js', 'external');
}
| improve this answer | |
  • I get a javascript error when using this function, when i put the script inside (footer) html.tpl.php it is working. – JurgenR Jan 10 '12 at 9:23
  • What error? Does Drupal output the correct looking script markup when using this function if you check the source code? – drmonkeyninja Jan 10 '12 at 9:28
  • Adding the options array fixed it. Guess it was a problem with weight. drupal_add_js('cdn.jquerytools.org/1.2.6/jquery.tools.min.js', array('type' => 'external', 'scope' => 'header', 'weight' => 10)); Thnx! – JurgenR Jan 10 '12 at 9:37
  • @Jurgen drupal_add_js() accepts also a string as second parameter; in that case, it is considered as the "type" index used from the $options array. If you need to set other options, then you have to use an array. – kiamlaluno Jan 31 '12 at 18:29
  • @drmonkeyninja How to add JS in any module..?? – Nishant Oct 10 '14 at 10:59
2

The method of adding javascript depends on for what you are adding javascript for. There are different ways to add js.

  • By defining in the theme.info file.

  • Adding it inline.

  • Adding an external js file.

You can add a js info file with this simple line of code

scripts[] = js/myscript.js

Or you can use the php function provided by drupal drupal_add_js

This functions lets you easily add a JavaScript file or helps in setting an inline code to any page in your theme and it takes 5 parameters (you see it in the api reference).

There is an detail post on this here.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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