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

1.2k Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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.

  • async : script fetched asynchronously, then HTML parsing is paused to execute the script, then parsing resumes.

  • defer : script fetched asynchronously and executed only after HTML parsing is done.

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