17

How can I add JavaScript scripts to bottom of a page, in my template?

1
  • array('type' => 'inline', 'scope' => 'footer', 'weight' => 5). You can use Weight to adjust your file in footer.
    – Kalidasan
    Mar 21, 2014 at 8:09

5 Answers 5

19

I think you can do it with drupal_add_js(); it seems that the scope key option is your friend!

5
  • 5
    I'm using it :drupal_add_js($theme_path.'/js/jquery.easing.1.3.js', array('type' => 'file', 'scope' => 'footer')); ?>
    – Onita
    May 6, 2011 at 7:26
  • @Onite where we have to put this? at html.tpl.php?
    – john
    Sep 29, 2011 at 1:49
  • 2
    At page.tpl.php
    – Onita
    Oct 6, 2011 at 8:09
  • 1
    Is it the same code if I want to attach a js file on template.php?
    – CocoSkin
    Aug 5, 2014 at 14:26
  • Would this not be overwritten when the theme is updated?
    – isherwood
    Jun 9, 2016 at 14:58
6

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.

3
  • 2
    I 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
  • 1
    no, 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
    – Alex Weber
    May 5, 2011 at 23:24
  • 3
    Some 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
5

You can try adding the file like this:

drupal_add_js('sites/all/themes/themname/js/skrollr.js', array('scope'=>'footer'));
2

It's worth looking at using this module here to manage that for you https://drupal.org/project/advagg

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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