Link, Style and Script Tags

HTML can accomplish a great deal in providing the structure of your site - however, almost all non-trivial projects will need the help of CSS for style and JavaScript for behavior/functionality. There are special tags for including or referencing CSS and JavaScript files on your web site.

The simplest of these tags is the <style> tag. You place it in the <head> of your document, and list any CSS style rules you’d like to use in between the opening and closing <style> tags. Here’s a quick example of doing this:

                    	
...
<head>
	<style>
		a {
			font-weight: bold;
		}
		div.sections {
			border: 1px solid lime;
		}
	</style>
</head>
…
						
					

Generally, while it is okay to have a couple of CSS rules in a <style> tag in your HTML file, you’re better off listing large sets of CSS rules in a dedicated .css file. There’s an easy way to include external CSS files on your site by using the <link> tag, in the <head> of your page:

                    	
...
<head>
	<link type=”text/css” rel=”stylesheet” href=”css/myStyles.css” />
</head>
…
						
                    

The <link> tag has three main attributes: “type”, which is always “text/css”, “rel”, which is generally “stylesheet”, and an “href” attribute that point to the CSS file. The location of the CSS file is relative to the location of the HTML file that contains the <link> tag.

Using this method will keep your styles nicely separated from the structure of your website. The same applies to JavaScript code - in this first example, we’ll take a look at the <script> tag, with code local to the page. The <script> tag can appear in the <head> or the <body>, as shown here:

                    	
<html>
	<head>
		<title>Test JS Page</title>
		<script type=”text/javascript”>
			alert(‘JS in Head’);
		</script>
	</head>
	<body>
		<script type=”text/javascript”>
			alert(‘JS in Body’);
</script>
	</body>
</html>
						
                    

Unlike CSS, there are some distinct advantages to including script tags in the body of your page; loading of the page will not be blocked or delayed by the time it takes to run the script tag, meaning your page might appear to load faster. The problem is, your HTML page can get quite messy with a lot of <script> tags around.

A better way to include large scripts in your page is to reference an external script using the <script> tag in the <head> of your page:

                    	
...
<head>
	<script type=”text/javascript” src=”myJS/test.js”></script>
</head>
…
						
                    

The script tag always has an attribute for “type”, which is primarily “text/javascript”. Externally loaded <script> tags also have an attribute for the source of the JS file, “src”, which is the location of the script tag relative to your HTML page.