JavaScript – How to Include JavaScript File Using Script Tag

javascript

I generally include JavaScript files using the script tag as below.

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

I have seen some people using the language attribute as well.

Now-a-days I find many people omitting the type attribute. I have started to get a feeling that if JavaScript is the default scripting language then even I should omit the type attribute. Would it be good to omit the type attribute? Would it cause any problems?

Best Answer

Take a look at this as a reference (Book of Speed): http://www.bookofspeed.com/chapter3.html

Essentially the best way is to combine all your javascript into one file called something like all.min.js that is also minimized.

Typically in HTML5 you would do something like:

<script src="js/all.min.js"></script>

As you can see, you DO NOT need the type attribute in HTML5, but you do in other versions of HTML and XHTML. The spec clarifies that if the content is other than "text/javascript" then you need to specify the type attribute, in HTML5.

Some things to remember:

Note:

If you are going to specify another type other than text/javascript you would use one of the following:

  • "application/ecmascript"
  • "application/javascript"
  • "application/x-ecmascript"
  • "application/x-javascript"
  • "text/ecmascript" "text/javascript"
  • "text/javascript1.0"
  • "text/javascript1.1"
  • "text/javascript1.2"
  • "text/javascript1.3"
  • "text/javascript1.4"
  • "text/javascript1.5"
  • "text/jscript"
  • "text/livescript"
  • "text/x-ecmascript"
  • "text/x-javascript"
  • "text/javascript;e4x=1"

The above list is from: http://dev.w3.org/html5/spec-author-view/the-script-element.html#scriptingLanguages

Remember that you would not use the language attribute, only the type attribute.