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.

Notes

Scripts without async , defer or type="module" attributes, as well as inline scripts, are fetched and executed immediately, before the browser continues to parse the page.

The script should be served with the text/javascript MIME type, but browsers are lenient and only block them if the script is served with an image type (image/*); a video type (video/*); an audio (audio/*) type; or text/csv. If the script is blocked, an error is sent to the element, if not a load event is sent.