In Google's PageSpeed reports that there are some Blocking Javascript required to be async. From this article I knew that I have to place async attribute to my scripts tag:
<script async src="http://third-party.com/resource.js"></script>
In cakePHP, I don't able to achieve this exactly, I just able to get:
<script async="async" src="http://third-party.com/resource.js"></script>
Using the Html's script method as follows:
$html->script(array('jsfile1', 'jsfile2'), array('async' => 'async'));
I tried array('async')
but it prints out 0='0' in the script tag
How could I make it print just async
in the script tag. Also, how could I make it available in the link tag of css too?
Notice: I use CakePHP 1.3x
Checking the source code indicates that there is no way to implement such tag as it's obvious that the format of attributes is %s="%s"
.
If you really need this I think the easiest way now is to provide your own customized HtmlHelper
by extending the core HtmlHelper
, and overwrite the _formatAttribute
function:
Note: this is for CakePHP 1.3.x only and it's pretty messy as it can't specify className
in the helpers array. CakePHP 2.x provides a cleaner way to overwrite default core helper with ease, but it's not what OP wanted so I'll not put it up here
Create 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);
}
}
In your app_controller.php
or whatever main controller that need this, use the CustomHtmlHelper
by:
var $helpers = array('CustomHtml');
And in your view, you can now start using async
or defer
tag. Feel free to extend this array if you see fit.
echo $this->CustomHtml->script('test', array('async' => 'async'));