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

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']);
  }        
}
  • 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? – sf_admin819 Aug 29 '16 at 20:24
  • Paste your code here, then will be able to tell you. – Love Huria Aug 30 '16 at 9:41
  • I have added it to the description. – sf_admin819 Aug 31 '16 at 3:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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