Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Including external javascript files in drupal 6

Parent Feed: 

In D7, drupal_add_js can handle external javascript files, but in D6 it cannot handle external js in a nice way.

Most people instead include external js with a preprocess_page function, or hook_footer. However, in both cases, the external js is added before the scripts added by drupal_add_js (the $scripts page template variable) which can be a performance problem.

I've seen one kind of nasty workaround that (ab)uses drupal_add_js to make a call to document.write:

http://www.wootenswebdesign.com/load-external-js-file-drupal-6

Here's another technique to include an external script with drupal_add_js in Drupal 6 that I find a little more readable.

Create a local js file (in your module or theme) and include that with drupal_add_js:

drupal_add_js(drupal_get_path('module', 'my_module') . '/my_module.js', 'module');

In your local js file, create a new script element and append it to the body:

(function ($) {
  Drupal.behaviors.myModule = function(context) {
    var externalScript = $('<script></script>').attr('type','text/javascript').attr('src', 'http://example.org/example.js');
    $('body').append(externalScript);
  }
}(jQuery));

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web