How to conditionally not load js for anonymous users? We have a situation where our contrib modules are being loaded for the anonymous user, but they are not needed. As a result, we are seeing higher page load times. We tried using hook_js_alter in a custom module with the code below. What is the proper way to not load the js files we don't need for the anonymous user?

mymodule_js_alter($javascript) {

  $javascript['somefile']['weight']=50;
  $javascript['somefile']['scope']=bottom; //region for bottom of the page

}


Current code:

function mymodule_js_alter(&amp;$javascript) {

    if(user_is_anonymous()){ 
       unset($javascript['sites/all/modules/contrib/autocomplete/autocomplete.js']); 
     } 
 }
If you don't want to load your JS in anonymous user, check the user if its logged in then load the JS file if its true. use user_is_logged_in() to check if user is logged in, place it inside your hook_preprocess_page().

Example:


  $theme_path = drupal_get_path('theme', 'zen');
  // This will load only in authenticated user.
  if(user_is_logged_in()) {
    drupal_add_js($theme_path . '/plugins/jQuery/jquery-2.2.3.min.js');
  }