gpt4 book ai didi

javascript - 德鲁帕尔 7 : how do I add the async attribute to an external JS script when using drupal_add_js?

转载 作者:行者123 更新时间:2023-11-30 20:02:10 24 4
gpt4 key购买 nike

我试过:

  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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com