在Google的PageSpeed报告中,有一些阻塞Javascript需要异步。从这篇文章中我知道我必须将异步属性放在我的脚本标签中:
<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
检查源代码表明无法实现这样的标签,因为很明显属性的格式是%s="%s"
。
如果你真的需要这个,我认为现在最简单的方法是通过扩展核心HtmlHelper
来提供你自己的自定义HtmlHelper
,并覆盖_formatAttribute
功能:
注意:这仅适用于 CakePHP 1.3.x,它非常混乱,因为它无法在辅助器数组中指定className
。CakePHP 2.x 提供了一种更简洁的方式来轻松覆盖默认的核心助手,但这不是 OP 想要的,所以我不会把它放在这里
-
创建
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); } }
-
在您的
app_controller.php
或任何需要此功能的主控制器中,通过以下方式使用CustomHtmlHelper
:var $helpers = array('CustomHtml');
-
在您看来,您现在可以开始使用
async
或defer
标签。如果您认为合适,请随意扩展此阵列。echo $this->CustomHtml->script('test', array('async' => 'async'));