【问题标题】:Drupal 7: how do I add the async attribute to an external JS script when using drupal_add_js?Drupal 7:使用 drupal_add_js 时如何将 async 属性添加到外部 JS 脚本?
【发布时间】:2018-11-12 05:34:36
【问题描述】:
我试过了:
drupal_add_js('http://somesite.com/pages/scripts/0080/8579.js', [
'type' => 'external',
'async' => TRUE
]);
和
drupal_add_js('http://somesite.com/pages/scripts/0080/8579.js', [
'type' => 'external',
'async' => 'async'
]);
没有结果。
有谁知道我是怎么做到的吗?
【问题讨论】:
标签:
javascript
drupal
drupal-7
drupal-hooks
【解决方案1】:
您不能仅通过指定选项来实现这一点,因为drupal_add_js() 不支持async 属性。
建议使用 defer 更好(恕我直言),因为它不会阻止 HTML 解析。
但是,如果你真的需要async 属性,你可以实现hook_preprocess_html_tag 来改变主题变量,像这样:
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';
}
}