Linking JavaScript and CSS files

As well as hopefully helping other people out, one objectives of this blog is to act as an aide-memoire as I often find myself looking up the same things on Google over and over again, or thinking “I knew how to do that two months ago”. So, I’ve included a category called “Aides-Memoires” which contains posts only intended to jog my memory so that I don’t have to keep repeating the same Google searches. This post is the first of this type.

Despite being heavily involved in development using web-technologies for over 10 years, one thing I can never seem to remember is how to declare JavaScript and CSS files in the section of my HTML pages. This is extremely basic stuff but I can never remember the syntax! So, here is my aide-memoire:

JavaScript:

<script language="javascript" type="text/javascript" src="scripts/myScripts.js"></script>

CSS:

<link rel="stylesheet" type="text/css" href="styles/myStyles.css" />

Notice that in the above examples the linked JavaScript and CSS files need to be in folders called ‘scripts’ and ‘styles’ respectively in order for the links to work, and that these folders must exist at the same level as the page that is referencing them. If you were to move the referencing page to a sub-folder on the web-server for example, your linked files would no longer be accessible. I would call this a brittle solution.

If you’re lucky enough to be using ASP.NET MVC you also have the option of getting the .NET Framework to work out the relative paths to the files you need to reference. If you’re using the Razor engine, this is coded as follows:

JavaScript:

<script language="javascript" type="text/javascript" src="@Url.Content("~/scripts/myScripts.js")"></script> 

CSS:

<link rel="stylesheet" type="text/css" href="@Url.Content("~/styles/myStyles.css")" />

The tilde (~) simply means “start from the root level of my website”. This is a far less brittle solution.

Update:

I’ve just read that the Razor version 2 engine in ASP.NET MVC 4 is smart enough to not need the @Url.Content() helper. It automatically resolves tildas, so the following will suffice:

<script language="javascript" type="text/javascript" src="~/scripts/myScripts.js" ></script>

CSS:

<link rel="stylesheet" type="text/css" href="~/styles/myStyles.css" />

As well as being robust when files are moved around, an added benefit is that Intellisense still works correctly.

Leave a Reply

Your email address will not be published. Required fields are marked *