如何为Haml的:javascript区块添加defer/async属性?
在Haml中为:javascript区块添加defer/async属性
当然可以实现!Haml支持直接给:javascript过滤器传递HTML属性参数,轻松给生成的<script>标签加上defer或async属性。
具体写法示例
1. 添加defer属性
你给出的写法完全没问题,生成的HTML会自动带上defer属性:
%body %div etc etc :javascript{defer: true} $(document).ready(function() { // whatever JS code });
对应的HTML输出是:
<body> <div>etc etc</div> <script defer> $(document).ready(function() { // whatever JS code }); </script> </body>
2. 添加async属性
同理,把参数换成async: true,就能给<script>标签加上async属性:
%body %div etc etc :javascript{async: true} $(document).ready(function() { // whatever JS code });
小提示
- 要是需要给
<script>加其他属性(比如type="module"),同样可以用这种方式传递,比如:javascript{defer: true, type: 'module'}。 - 别同时加
defer和async哦,二者的执行逻辑不一样,浏览器会优先按async的规则来处理。
内容的提问来源于stack exchange,提问作者Vasco
相关产品推荐
相关产品推荐

