loader image
Skip to main content
If you continue browsing this website, you agree to our policies:
x
Completion requirements

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.

Examples

Embedding data in HTML

You can also use the <script> element to embed data in HTML with server-side rendering by specifying a valid non-JavaScript MIME type in the type attribute.

<!-- Generated by the server -->
<script id="data" type="application/json">{"userId":1234,"userName":"John Doe","memberSince":"2000-01-01T00:00:00.000Z"}</script>
<!-- Static -->
<script>
 const userInfo = JSON.parse(document.getElementById("data").text);
 console.log("User information: %o", userInfo);
</script>