Using separate files for CSS and JS

One of your classmates rightly noted that Nick and I have said that you can (and often should) keep your HTML, CSS, and JavaScript in separate files, but have not provided any instructions about how to do that.

Single File

Using a single file for HTML, CSS, and JS
Using a single file for HTML, CSS, and JS

The single-file approach is good for quick one-off tests or demonstrations. This is where you put all your CSS and JavaScript in the same file as your HTML. Your single .html document will look something like this:

<html>
<head>
    <style type="text/css">
    /* CSS goes here in the style tag. */
    </style>

    <script type="text/javascript">
    // JavaScript goes here in the script tag.
    </script>
</head>
<body>
    HTML content goes here in the body tag.
</body>
</html>

Although it is fast to get started and there are fewer files to keep track of, there are some significant downsides to keeping everything in one HTML file. For example, if you put your CSS and JavaScript in the same file with your HTML, you can’t reuse the same styles and code on other pages without needless duplication.

Multiple Files

Multiple Files for HTML, CSS, and JS
Multiple Files for HTML, CSS, and JS

The alternative is to store your HTML, CSS, and JavaScript in separate files. In the main .html file you use a <link> tag to include the external stylesheet and a <script> tag to include the external JavaScript. Now your .html document will look like this:

<html>
<head>
    <link rel="stylesheet" href="file.css" type="text/css" media="screen" />
    <script type="text/javascript" src="file.js"></script>
</head>
<body>
    HTML content goes here in the body tag.
</body>
</html>

Note that the CSS file is specified by href="..." while the JavaScript file is specified by src="..."


Posted

in

by

Tags: