作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试过:
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'
]);
没有结果。
有人知道我怎样才能做到这一点吗?
最佳答案
您不能仅通过指定选项来实现此目的,因为 drupal_add_js()
不支持 async
属性。
建议使用 defer
,它(恕我直言)更好,因为它不会阻止 HTML 解析。
async
:异步获取脚本,然后暂停 HTML 解析以执行脚本,然后继续解析。
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';
}
}
关于javascript - 德鲁帕尔 7 : how do I add the async attribute to an external JS script when using drupal_add_js?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53256412/
我是一名优秀的程序员,十分优秀!