Javascript Drupal 7:在使用Drupal_add_JS时,如何将async属性添加到外部JS脚本?

Javascript Drupal 7:在使用Drupal_add_JS时,如何将async属性添加到外部JS脚本?,javascript,drupal,drupal-7,drupal-hooks,Javascript,Drupal,Drupal 7,Drupal Hooks,我试过: drupal_add_js('http://somesite.com/pages/scripts/0080/8579.js', [ 'type' => 'external', 'async' => TRUE ]); 及 没有结果 有人知道我是如何做到这一点的吗?仅通过指定选项是无法做到的,因为drupal\u add\u js()不支持async属性 建议使用延迟,因为它不会阻止HTML解析,所以(imho)更好 async:异步获取脚本,然后暂

我试过:

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

没有结果


有人知道我是如何做到这一点的吗?

仅通过指定选项是无法做到的,因为
drupal\u add\u js()
不支持
async
属性

建议使用
延迟
,因为它不会阻止HTML解析,所以(imho)更好

  • async
    :异步获取脚本,然后暂停HTML解析以执行脚本,然后继续解析

  • defer
    :异步获取脚本,并仅在完成HTML解析后执行

但是,如果确实需要
async
属性,可以实现
hook\u preprocess\u html\u标记来更改主题变量,如下所示:

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