在附加js文件时使用headscript()添加属性attributes

Add attribute attributes while appending a js file using headscript()

本文关键字:headscript 添加 attributes 属性 js 文件      更新时间:2023-09-26

这是我第一次使用php。我试图优化js在一个网站,我看到headscript()附加js文件。

echo $this->headScript()->appendFile('/js/image-gallery/jquery.simplemodal.1.4.4.min.js');

在这个我试图添加一个属性的脚本标签附加

$this->headScript()->setAllowArbitraryAttributes(true);
echo $this->headScript()->appendFile('/js/image-gallery/jquery.simplemodal.1.4.4.min.js', 

我也试过

$this->headScript()->setAllowArbitraryAttributes(true);
echo $this->headScript()->appendFile('/js/image-gallery/jquery.simplemodal.1.4.4.min.js',$attrs = array("async" => "true"))

array("async" => "true");

文件

php部分

    <?php
    $this->headScript()->setAllowArbitraryAttributes(true);
    echo $this->headScript()->appendFile('/js/image-gallery/jquery.simplemodal.1.4.4.min.js', $attrs = array("async" => "true"));
    ?>

我期望输出是

<script async="true" src="/js/image-gallery/jquery.simplemodal.1.4.4.min.js"></script>

我得到

<script type="Array" src="/js/image-gallery/jquery.simplemodal.1.4.4.min.js"></script>

如何解决?我找不到任何通过headscript();

添加属性的示例

您需要将这些属性作为第三个参数传递

$this->headScript()->appendFile(
  '/js/image-gallery/jquery.simplemodal.1.4.4.min.js', 
  null, 
  array('async' => 'true', 'foo' => 'bar')
); 

null这里是'type'属性,默认为text/javascript

看起来你正在使用Zend框架。如果有,请参考HeadScript Helper

您需要传递属性为$attrs = array()

appendFile($src, $type = 'text/javascript', $attrs = array())
所以你的代码应该是 <<p> 更新代码/strong>
echo $this->headScript()->appendFile('/js/image-gallery/jquery.simplemodal.1.4.4.min.js',  $type = 'text/javascript', $attrs = array("async" => "true"));

代替

echo $this->headScript()->appendFile('/js/image-gallery/jquery.simplemodal.1.4.4.min.js', array("async" => "true"));

默认禁用任意属性。要允许这样的属性,您可以通过setAllowArbitraryAttributes()方法启用它们:

$this->headScript()->setAllowArbitraryAttributes(true);
然后

echo $this->headScript()->appendFile('/js/image-gallery/jquery.simplemodal.1.4.4.min.js',  null, array("async" => "true"));