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

correctly adding defer attribute to script tag with pure javascript

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

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 属性,例如 defer=true 而不仅仅是 defer.

它们相同吗?如果我做 defer=true 而不是 defer,这意味着什么?

谢谢!

我会把它改成:

script.setAttribute("defer", "defer");

它们通常表现相同(尽管文档在技术上声明诸如 defer 之类的属性的值不应该是 "true" 或 false")——或者至少在我使用过布尔属性的任何浏览器中.属性defer通常在script标签中if present实现生效.其值被忽略.

话虽这么说,规范指定布尔属性的值不应存在,否则应设置为其自身,没有前导/尾随空格(大小写不事情)。因此,动态设置时,最好将值保留为属性的名称。

请参阅此文档了解布尔属性 (HTML5):https://www.w3.org/TR/html5/infrastructure.html#boolean-attribute

引用该文档:

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.

更新: 看起来如果将属性设置为空字符串,它会添加没有值的属性。这也是一种选择。

这对我有用:(chrome 94)

script.defer = true;

如果您已有脚本标签并想添加defer/async属性。然后使用此代码。

window.addEventListener('load', (event) => {
    var fbChatScript = document.querySelector('#facebook-jssdk');
    fbChatScript.setAttribute('defer', '');
});