gpt4 book ai didi

php - CakePHP 将异步添加到脚本标签

转载 作者:行者123 更新时间:2023-12-02 04:50:29 24 4
gpt4 key购买 nike

在 Google 的 PageSpeed 报告中,有一些 Blocking Javascript 需要异步。来自 this article我知道我必须将异步属性放置到我的脚本标签中:

<script async src="http://third-party.com/resource.js"></script>

在 cakePHP 中,我无法完全实现这一点,我只能得到:

<script async="async" src="http://third-party.com/resource.js"></script>

使用Html的脚本方法如下:

$html->script(array('jsfile1', 'jsfile2'), array('async' => 'async'));

我尝试了 array('async') 但它在脚本标记中打印出 0='0'

我怎样才能让它在脚本标签中只打印 async 。另外,我怎样才能让它在 css 的链接标签中也可用?

注意:我使用的是 CakePHP 1.3x

最佳答案

Checking the source code表示没有办法实现这样的标签,因为很明显属性的格式是%s="%s"

如果你真的需要这个,我认为现在最简单的方法是通过扩展核心 HtmlHelper 来提供你自己的自定义 HtmlHelper,并覆盖 _formatAttribute 功能:

注意:这仅适用于 CakePHP 1.3.x,而且它非常困惑,因为它不能在 helpers 数组中指定 className。 CakePHP 2.x 提供了一种更简洁的方法来轻松覆盖默认的核心助手,但这不是 OP 想要的,所以我不会把它放在这里

  1. 创建 app/views/helpers/custom_html.php:

    <?php
    App::import('Helper', 'Html');
    class CustomHtmlHelper extends HtmlHelper {
    function __formatAttribute($key, $value, $escape = true) {
    if (in_array($key, array('async', 'defer'))) {
    return $key;
    }
    return parent::__formatAttribute($key, $value, $escape);
    }
    }
  2. 在您的 app_controller.php 或任何需要它的主 Controller 中,通过以下方式使用 CustomHtmlHelper:

    var $helpers = array('CustomHtml');
  3. 在您看来,您现在可以开始使用 asyncdefer 标签。如果您认为合适,请随意扩展此数组。

    echo $this->CustomHtml->script('test', array('async' => 'async'));

关于php - CakePHP 将异步添加到脚本标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18945675/

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