dongying3830 2013-09-22 15:48
浏览 29
已采纳

CakePHP向脚本标记添加异步

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

  • 写回答

1条回答 默认 最新

  • doutian3269 2013-09-23 02:01
    关注

    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

    1. 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);
          }
      }
      
    2. In your app_controller.php or whatever main controller that need this, use the CustomHtmlHelper by:

      var $helpers = array('CustomHtml');
      
    3. 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'));
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题