Search code examples
drupaldrupal-6external-scripthtml-head

Load external script in <head> in Drupal 6


I want to load an external script in <head>. It is module specific so I want my module to take care of the loading.

In Drupal 6, function drupal_add_js() does not allow to add an external script in <head>. It will be available in Drupal 7 passing the "external" argument to the function. In D6, I can use drupal_set_html_head() instead, but it inserts the given data in the beginning of the <head> which I don't want. I'd like to append data in it.

It turned out that drupal_html_set_head() appends data.

$stored_head .= $data ."\n";

So the behavior I experimented--data was inserted in the beginning of head data--should come from that I call drupal_html_set_head() in my module's hook_init() function.

How can I append data to the very and of <head>?


Solution

  • The default page.tpl.php (you can find it in /modules/system/page.tpl.php is this:

    <head>
      <title><?php print $head_title; ?></title>
      <?php print $head; ?>
      <?php print $styles; ?>
      <?php print $scripts; ?>
      <script type="text/javascript"><?php /* Needed to avoid Flash of Unstyled Content in IE */ ?> </script>
    </head>
    

    When you make drupal_set_html_head() it is appending stuff to variable $head, but still there are more variables appended as you see.

    One possible solutions is to append the stuff that you want to $scripts, instead of $head.

    How?

    with a preprocess function from your module:

    function MYMODULE_preprocess_page(&$variables) {
        $variables['scripts'] .= $your_stuff;
    }
    

    I didn't try this solution, but if doesn't work maybe is because the order of execution. Try to set your module's weight higher, so it will run after the system_preprocess_page.

    Other reason why may not work is because the theme is printing the variables in different order in page.tpl.php. But you can't control this from the code of a module.