Igor Simic
6 years ago

How to dynamically add JavaScript in Drupal and exclude it from caching


Sometimes it is needed to include JS to Drupal 7 frontend but exclude it from caching. 
So, to add javascript dynamically but not cache it, the best is to use _menu hook and let Drupal insert it automatically to frontend. 

The idea is to create custom item and set url which will be used by Drupal to 'load' JS, we will also define the callback function which will output your JS code and finally we will use drupal_add_js to wrap it up.


First let's create function in _menu hook:
function my_plugin_menu() {

    $items = array();

    //
    $items['plugin_url/test.js'] = array(
        'title' => 'JS Test',
        'page callback' => 'callback_function',
        'access arguments' => array('access content'),
         'type' => MENU_CALLBACK,
    );
    
     
  return $items;
}

now we can create callback function where you can put your dynamic JS code:
function callback_function(){
  $str_js = 'console.log("this is not cached");';
  return $str_js; 
}

next, let's use  drupal_add_js to insert this JS to frontent, and we can use cache=false in setting array to prevent JS from caching
drupal_add_js( "plugin_url/test.js", array('cache'=>false, 'scope' => 'footer', 'group' => 99,) ); // group 99 is optional used only in my case

If you reload your page you will see in your console our message, and if you are using caching, like boost cache this JS will not be cached