Why write <script type="text/javascript"> when the mime type is set by the server?
Solution 1:
Douglas Crockford says:
type="text/javascript"
This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.
He also says:
W3C did not adopt the
language
attribute, favoring instead atype
attribute which takes a MIME type. Unfortunately, the MIME type was not standardized, so it is sometimes"text/javascript"
or"application/ecmascript"
or something else. Fortunately, all browsers will always choose JavaScript as the default programming language, so it is always best to simply write<script>
. It is smallest, and it works on the most browsers.
For entertainment purposes only, I tried out the following five scripts
<script type="application/ecmascript">alert("1");</script>
<script type="text/javascript">alert("2");</script>
<script type="baloney">alert("3");</script>
<script type="">alert("4");</script>
<script >alert("5");</script>
On Chrome, all but script 3 (type="baloney"
) worked. IE8 did not run script 1 (type="application/ecmascript"
) or script 3. Based on my non-extensive sample of two browsers, it looks like you can safely ignore the type
attribute, but that it you use it you better use a legal (browser dependent) value.
Solution 2:
Because, at least in HTML 4.01 and XHTML 1(.1), the type
attribute for <script>
elements is required.
In HTML 5, type
is no longer required.
In fact, while you should use text/javascript
in your HTML source, many servers will send the file with Content-type: application/javascript
. Read more about these MIME types in RFC 4329.
Notice the difference between RFC 4329, that marked text/javascript
as obsolete and recommending the use of application/javascript
, and the reality in which some browsers freak out on <script>
elements containing type="application/javascript"
(in HTML source, not the HTTP Content-type header of the file that gets send). Recently, there was a discussion on the WHATWG mailing list about this discrepancy (HTML 5's type
defaults to text/javascript
), read these messages with subject Will you consider about RFC 4329?