1

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(&$javascript) {

    if(user_is_anonymous()){ 
       unset($javascript['sites/all/modules/contrib/autocomplete/autocomplete.js']); 
     } 
 }

2 Answers 2

2

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');
  }
1

You can use it like:

/**
 * Implements hook_js_alter().
*/
function hook_js_alter(&$javascript) {
// Removes the js for anonymous users.
  if(user_is_anonymous()) {  
    unset($javascript['sites/all/theme/js/file.js']);
  }        
}
3
  • I tried using the code above (even after cache clear) and it did not work. For the anonymous user it was still loading the js file I wanted to exclude. What I did was I logged out and opened incognito mode, but still found the JS to be loaded for anonymous users. Are there any other steps I am missing? Aug 29, 2016 at 20:24
  • Paste your code here, then will be able to tell you.
    – Love Huria
    Aug 30, 2016 at 9:41
  • I have added it to the description. Aug 31, 2016 at 3:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.