javascriptdrupaldrupal-7drupal-hooks

Drupal 7: how do I add the async attribute to an external JS script when using drupal_add_js?


I've tried:

  drupal_add_js('http://somesite.com/pages/scripts/0080/8579.js', [
    'type' => 'external',
    'async' => TRUE
  ]);

and

  drupal_add_js('http://somesite.com/pages/scripts/0080/8579.js', [
    'type' => 'external',
    'async' => 'async'
  ]);

With no results.

Would any know how I could achieve this?


Solution

  • You can't achieve this just by specifying the option because drupal_add_js() does not support async attribute.

    It is recommended to use defer which is (imho) better because it doesn't block HTML parsing.

    However, if you really need the async attribute, you can implement the hook_preprocess_html_tag to alter the theme variables, like so :

    function moduleortheme_preprocess_html_tag(&$variables) {
      $el = &$variables['element'];
      if ($el['#tag'] !== 'script' || empty($el['#attributes']['src'])) {
        return;
      }   
    
      # External scripts to load asynchronously
      $async = [
        'http://somesite.com/pages/scripts/0080/8579.js',
        #...
      ];
    
      if (in_array($el['#attributes']['src'], $async)) {
        $el['#attributes']['async'] = 'async';
      }
    }