简体   繁体   English

在动态创建脚本时,我们还需要“script.type ='text / javascript”吗?

[英]Do we still need “script.type='text/javascript” when creating a script dynamically?

The code is like this: 代码是这样的:

var script = document.createElement('script');
//script.type = 'text/javascript'; // do I need this ?
script.src = src;
document.body.appendChild(script);

The second line has been commented out because it makes no difference to have it. 第二行已被注释掉,因为它没有任何区别。 Or am I missing something ? 或者我错过了什么?

Thanks, 谢谢,

No: The default value of type is already set to JavaScript ("text/javascript"). 否: type的默认值已设置为JavaScript(“text / javascript”)。 The type attribute is a property of the SCRIPT tag to allow Vbscript, for example, which is only supported by IE. type属性是SCRIPT标记的一个属性,允许Vbscript,例如,只有IE支持。

The type attribute has also become optional in HTML5. type属性在HTML5中也是可选的。 This could be an encouragement to omit the type attribute of the script element. 这可能是一种省略script元素的type属性的鼓励。

No. It's probably not strictly correct in html4 but it shouldn't cause you any problems. 不。它可能在html4中并不完全正确,但它不会给你带来任何问题。

HTML5 Spec HTML5规范

"The type attribute gives the language of the script or format of the data..." 
"...The default, which is used if the attribute is absent, is 'text/javascript'."

The only thing I have noticed is that IDE's sometimes don't use the correct syntax highlighting when you don't specify a type. 我唯一注意到的是,当您未指定类型时,IDE有时不会使用正确的语法突出显示。 I have found this in Coda for the Mac, it's the only reason I ever put it in now. 我在Coda for Mac中找到了这个,这是我现在把它放进去的唯一原因。

Browsers will work without it. 浏览器没有它就能工作。

If you are generating HTML 4 or XHTML 1 then leaving it out would be non-conformant. 如果您正在生成HTML 4或XHTML 1,那么将其删除将是不符合要求的。

If you are generating HTML, then it is explicitly optional. 如果要生成HTML,那么它是显式可选的。

HTML 4和XHTML中需要type attribute ,但HTML5中是可选的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM