CakePHP向脚本标记添加异步

时间:2013-09-22 15:48:03

标签: php cakephp asynchronous cakephp-1.3

在Google的PageSpeed报告中,有一些阻止Javascript需要异步。从this article我知道我必须将async属性放在我的脚本标记中:

<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

1 个答案:

答案 0 :(得分:5)

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或任何需要此功能的主控制器中,使用CustomHtmlHelper by:

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

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