Using the <script> Element to Link External Files

The second way is to place JavaScript code in an external file and import it into the document. The second method is preferred because, with large programs, it is hard to maintain everything in an HTML document. JavaScript files have the file extension ".js". An example is:

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

Although all JavaScript code should be in a .js file because our programs are short, we'll place code directly within a <script> tag. We'll use external .js files in the next course.

<script>: The Script element

The <script> HTML element is used to embed executable code or data; this is typically used to embed or refer to JavaScript code. The  <script> element can also be used with other languages, such as WebGL's GLSL shader programming language and JSON.

Content categories Metadata content, Flow content, Phrasing content.
Permitted content Dynamic script such as text/javascript.
Tag omission None, both the starting and ending tag are mandatory.
Permitted parents Any element that accepts metadata content, or any element that accepts phrasing content.
Implicit ARIA role No corresponding role
Permitted ARIA roles No role permitted
DOM interface HTMLScriptElement


Source: Mozilla, https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script
Creative Commons License This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.