Embedding JavaScript in HTML

2005-05, 2008-05

Here's how to embed JavaScript into HTML. There are a few variations. If you just have few lines of code, do:

<script type="application/javascript">
alert("hi ya!");
</script>

If you have a lot code, you can put them in a file, and call it like this:

<script type="application/javascript" src="mycode.js"></script>

In practice, you'll see “type="text/javascript"” instead of “type="application/javascript"”. The “text” is still ok, but has been deprecated since 2006-04.

Of existing code on the web, you will also see:

<script language="JavaScript">...</script>

or just

<script>...</script>

The “language=” is the original specification when Netscape invented JavaScript. Later on, standard bodies invented the “type=” and made it a required attribute. However, as of 2005-08, major websites do not clearly show any of them winning the popularity contest:

For all practical purposes, one can just use <script> and it doesn't make any difference. If you want your code to conform to w3c standard, use “<script type="application/javascript">”. This is recommended in RFC4329 (published in 2006-04), which also declares “text/javascript” as obsolete.

Reference:


Page created: 2005-05.
© 2005 by Xah Lee.
Xah Signet