Drupal Tutorial: Include custom JavaScript files

Adding inline JavaScript such as Google Analytics or DoubleClick to a Drupal site is a trivial task using the inbuilt Drupal function named drupal_add_js(). This function is flexible enough to cope with adding a variety of JavaScript files whether they are third-party or locally referenced scripts.

Here are some use cases and useful snippets that could be added to your theme's template.php file.

Google Analytics

  $ga  = "var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'YOUR-ACCOUNT-IDENTIFIER']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();";

  drupal_add_js($ga, array('type' => 'inline', 'scope' => 'footer'));

ShareThis.com buttons

    $st1  = "var switchTo5x=false;";
    drupal_add_js($st1, array('type' => 'inline', 'scope' => 'header'));
    drupal_add_js("http://w.sharethis.com/button/buttons.js");
    $st2  = "stLight.options({publisher: 'YOUR-PUBLISHER-ID', doNotHash: false, doNotCopy: false, hashAddressBar: false});";
    drupal_add_js($st2, array('type' => 'inline', 'scope' => 'header'));

Custom font from Typekit.net

    drupal_add_js('http://use.typekit.net/example.js', array( 'type' => 'external', 'scope' => 'header') );
    $typekit_init = 'try{Typekit.load();}catch(e){}';
    drupal_add_js($typekit_init, array('type' => 'inline', 'scope' => 'header'));

Google Maps

    if ( preg_match('/contact/', $_SERVER['REQUEST_URI'])) {
        drupal_add_js('https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false', array( 'scope' => 'footer', 'type' => 'external') );
        drupal_add_js(path_to_theme() . '/js/contact.js', array( 'scope' => 'footer'));
    }