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"). The type attribute is a property of the SCRIPT tag to allow Vbscript, for example, which is only supported by IE.
The type
attribute has also become optional in HTML5. This could be an encouragement to omit the type
attribute of the script
element.
No. It's probably not strictly correct in html4 but it shouldn't cause you any problems.
HTML5 Spec
"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. I have found this in Coda for the Mac, it's the only reason I ever put it in now.
Browsers will work without it.
If you are generating HTML 4 or XHTML 1 then leaving it out would be non-conformant.
If you are generating HTML, then it is explicitly optional.
The type attribute
is required in HTML 4 and XHTML, but optional in HTML5.
精彩评论