How can I add JavaScript scripts to bottom of a page, in my template?
5 Answers
I think you can do it with drupal_add_js(); it seems that the scope key option is your friend!
-
5I'm using it :
drupal_add_js($theme_path.'/js/jquery.easing.1.3.js', array('type' => 'file', 'scope' => 'footer')); ?>
– OnitaMay 6, 2011 at 7:26 -
-
2
-
1
-
In your theme's html.tpl.php
there is a line <?php print $scripts; ?>
.
That's the line that prints out the javascript in your page.
You can move it around anywhere you like, for example, place it after everything else, just before the closing body
tag to have all your scripts load at the bottom.
-
2I would not suggest to print
$scripts
at the bottom of html.tpl.php; that variable includes the script tags for jQuery, and other Drupal JavaScript files. Does$scripts
contain HTML tags that can be output outside<head>
?– apaderno ♦May 5, 2011 at 23:18 -
1no, scripts only has 'script src' tags and inline javascript, it's done in a couple templates and works like a charm, ive done it in Zentropy, my html5 base theme: drupal.org/project/zentropy May 5, 2011 at 23:24
-
3Some JS files from contrib modules may assume being included in the page
<head>
. For instance when they are defining globals variables or function called by inline script (even if it's a bad practice). May 6, 2011 at 11:37
You can try adding the file like this:
drupal_add_js('sites/all/themes/themname/js/skrollr.js', array('scope'=>'footer'));
It's worth looking at using this module here to manage that for you https://drupal.org/project/advagg
I enabled AdvAgg Modifier and Advanced CSS/JS Aggregation. Then I visited settings page /admin/config/development/performance/advagg/mod
where I checked options:
Enable preprocess on all JS
Move all inline scripts to the bottom of the execution order
Move all browser conditional JavaScript to the bottom of the group
Move JS to the footer - All
And now I have all JS on the bottom (as Google recommends), without the need to change html.tpl.php
.
array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
. You can use Weight to adjust your file in footer.