2

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?

0

1 Answer 1

1

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';
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.