使用纯javascript正确地将defer属性添加到脚本标记
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用纯javascript正确地将defer属性添加到脚本标记,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1736字,纯文字阅读大概需要3分钟。
内容图文
所以我尝试添加这样的延迟脚本标签
const script = document.createElement('script');
script.setAttribute('src', '/script.js');
script.setAttribute('type', 'text/javascript');
script.setAttribute('defer', true);//this is the code in question!
document.getElementsByTagName('body')[0].appendChild(script);
但是我发现结果脚本标签会生成像defer = true这样的延迟属性,而不仅仅是延迟.
它们是一样的吗?如果我推迟=真而不是推迟,这意味着什么?
谢谢!
解决方法:
我会把它改成:
script.setAttribute("defer", "defer");
它们通常表现相同(尽管文档在技术上声明了属性的值,例如defer不应该是“true”或false“) – 或者至少在任何浏览器中我都使用了布尔属性.属性defer通常是实现的如果存在于脚本标记中,则生效.其值被忽略.
话虽这么说,规范指定布尔属性的值不应该存在,否则应该设置为自己,没有前导/尾随空格(情况无关紧要).因此,在动态设置时,最好将值保留为属性的名称.
有关布尔属性(HTML5),请参阅此文档:https://www.w3.org/TR/html5/infrastructure.html#boolean-attribute
从那个doc引用:
A number of attributes are boolean attributes. The presence of a boolean attribute on an element represents the true value, and the
absence of the attribute represents the false value.If the attribute is present, its value must either be the empty string
or a value that is an ASCII case-insensitive match for the attribute’s
canonical name, with no leading or trailing whitespace.Note: The values “true” and “false” are not allowed on boolean attributes.
To represent a false value, the attribute has to be omitted
altogether.这个defer属性的文档(HTML5):
https://www.w3.org/TR/html5/scripting-1.html#attr-script-defer它指出:
The async and defer attributes are boolean attributes that indicate how > the script should be executed.
更新:看起来如果将属性设置为空字符串,它将添加没有值的属性.这也是一种选择.
内容总结
以上是互联网集市为您收集整理的使用纯javascript正确地将defer属性添加到脚本标记全部内容,希望文章能够帮你解决使用纯javascript正确地将defer属性添加到脚本标记所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。