编程语言
首页 > 编程语言> > 使用纯javascript正确地将defer属性添加到脚本标记

使用纯javascript正确地将defer属性添加到脚本标记

作者:互联网

所以我尝试添加这样的延迟脚本标签

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,setattribute,script-tag,deferred-loading
来源: https://codeday.me/bug/20190527/1164390.html