title: Add js to a template file using theme preprocess
body: <p>I have a custom Drupal 7 module which is hooking into the <a href="http://drupal.org/project/media" rel="nofollow">media</a> module and I'm having trouble with adding some js into its render.</p>
  
  <p>The module is defining a theme like this:</p>
  
  <pre><code>function media_flash_theme($existing, $type, $theme, $path) {
    return array(
      'media_flash_video' =&gt; array(
        'variables' =&gt; array('uri' =&gt; NULL, 'options' =&gt; array()),
        'file' =&gt; 'media_flash.theme.inc',
        'path' =&gt; $path . '/includes/themes',
        'template' =&gt; 'media-flash',
      )
    );
  }
  </code></pre>
  
  <p>And my formatter (view) is returning my element like so:</p>
  
  <pre><code>$element = array(
    '#theme' =&gt; 'media_flash_video',
    '#uri' =&gt; $file-&gt;uri,
    '#options' =&gt; array(),
  );
  
  return $element;
  </code></pre>
  
  <p>Now, I have a preprocess function which adds some js:</p>
  
  <pre><code>function media_flash_preprocess_media_flash_video(&amp;$variables) {
  
    $path = libraries_get_path('swfobject');
    drupal_add_js($path . '/swfobject.js');
  
    ...
  }
  </code></pre>
  
  <p>And also a drupal add js in my template file:</p>
  
  <pre><code>/**
   * @file media_flash/includes/themes/media-flash.tpl.php
   */
  
  
  $javascript = '
  (function ($) {
  ...
  })(jQuery);
  ';
  
  drupal_add_js($javascript, 'inline');
  </code></pre>
  
  <p>The issue is weird. When I'm logged in then everything works fine, all the time. However, when I am using it as an anonymous user it all works fine the first load (after cache clear) but then the two javascripts arent added anymore.</p>
  
  <p>I have tried to change my preprocess function so it adds the javascript with this <code>$variables['scripts'] = drupal_get_js();</code> but this also has the same behaviour.</p>
  
  <p>Ive googled around a bit and found some suggestions but nothing's worked thus far. Any help is appreciated.</p>
  
  <p>Thanks,</p>
  
  <p>EDIT: So I looked into this a bit more and the code is being executed through the filter module. It seems as though the first time it gets executed it gets cached and then it is just recieved from the cache each time after that, so the drupal_add_js code isn't run again.</p>
  
  <p>Is there a way around this caching or do I need to remove my js from this part all together?</p>