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)更好
:异步获取脚本,然后暂停HTML解析以执行脚本,然后继续解析async
:异步获取脚本,并仅在完成HTML解析后执行defer
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';
}
}