Search code examples
javascripthtmldojo

How to specify script type in .js file?


In html files, you probably can write:

<script type="aaa/bbb" src="xyz.js"></script> language="javascript"

In JavaScript files (.js) it is just the raw JavaScript codes without specifying the type, is it assuming all types are "text/javascript"? What if you have typed like "aaa/bbb"?

Dojo is an example may require this.


Solution

  • Yes, in a JavaScript file you just write the code without any tags around it. It's the tag that includes the file in the page that specifies the type. So you might have:

    foo.js:

    function doSomethingReallyCool() {
       // ...
    }
    

    ...which you include like this:

    <script src="foo.js"></script>
    

    You can optionally specify the type on the script element:

    <script type="text/javascript" src="foo.js"></script>
    

    ...but in practice this is unnecessary for JavaScript, you'd only need it if you were referencing a file that wasn't JavaScript (like VBScript on IE).

    Note that the language attribute in your example was never part of any specification. Since HTML 4 (12 years ago), the correct way to indicate the language is via the type attribute.