I'm trying to insert reference to the Javascript file in the header by using drupal_add_js()
. I placed this line inside the template preprocess function in template.php. The result that the code is not working at all: There is no script link in output as it should be. Can anyone tell me what am I doing wrong?
function phptemplate_preprocess_page(&$vars) {
$url = drupal_get_path("theme","mysite");
drupal_add_js($url."/jquery.js");
drupal_add_js($url."/drupal.js");
.....
I'm trying to insert reference to the Javascript file in the header by using drupal_add_js()
. I placed this line inside the template preprocess function in template.php. The result that the code is not working at all: There is no script link in output as it should be. Can anyone tell me what am I doing wrong?
function phptemplate_preprocess_page(&$vars) {
$url = drupal_get_path("theme","mysite");
drupal_add_js($url."/jquery.js");
drupal_add_js($url."/drupal.js");
.....
Share
Improve this question
edited Oct 29, 2011 at 11:49
avpaderno
29.7k17 gold badges78 silver badges94 bronze badges
asked Apr 1, 2010 at 21:11
AndrewAndrew
1,0257 gold badges23 silver badges40 bronze badges
5 Answers
Reset to default 10Even easier, Javascript that needs to be loaded on all pages can be added in the theme's .info file. See http://drupal.org/node/171205#scripts.
drupal_add_js(path_to_theme().'/js/jquery.cycle.all.js');
$vars['scripts'] = drupal_get_js();
If you place the javascript file in the theme directory, you can just add the following to the themes .info file
scripts[] = myJavaScriptFile.js
After you add this file you need to deactivate your theme and then reactive it.
As pointed by other, simply using drupal_add_js()
from a hook_preprocess_page()
implementation doesn't work. The references to JavaScript files collected through the multiple calls to drupal_add_js()
are used to generate the corresponding markup into the $scripts
variables from template_preprocess_page()
. But a theme's implementation of hook_preprocess_page()
is always called after template_preprocess_page()
. So in order to have the files added through drupal_add_js()
in your .tpl.php
file(s), you need to override the already set $scripts
variables:
function THEME_preprocess_page(&$variables)
drupal_add_js(...);
$variables['scripts'] = drupal_get_js();
}
But, you shouldn't have to add jquery.js
and drupal.js
yourself, it should already be done automatically by Drupal core. If you need to do it yourself, then something is broken on your site. You can (re-)add the files as a quick fix, but you better find the root cause of the issue as it is most likely creating other issues you haven't yet identified (or worked around without realizing it).
drupal_add_js()
works, but you are putting it deep into the page rendering process. I suggest you put it in the template.php like you are doing, but in the beginning, outside any function. This is what we did on a few of our projects.