Where Should Your Code Live

by kirupa   |   8 February 2014

Let's take a break from our regularly scheduled...programming (ha!). Instead of looking at what goes into our code, in this tutorial, we are going to go a bit higher and look at something really basic. We are going to look at where exactly the code you write should live.

Onwards!

The Options on the Table

So far, all of the code we have been writing has been contained fully inside an HTML document:

javascirpt in document

In this world, the only thing that protects your HTML document from JavaScript is just a couple of script tags. Now, your JavaScript does not have to live inside your HTML document. You have another way, and this way involves a separate file where all of your JavaScript will instead live:

completely separate files

In this approach, you don't have any real JavaScript that lives inside your HTML document. You still have your script tag, but this tag simply points to the JavaScript file instead of containing line after line of actual JavaScript code.

Of course, none of these approaches are mutually exclusive. You can mix both approaches into an HTML document ad have a hybrid approach where you have both an external JavaScript file as well as lines of JavaScript code:

code mixed into a document

To make things more interesting, you also have variations on the two approaches such as having multiple script sections in a HTML document, having multiple JS files, and so on. In the following sections, we'll look at both of these approaches in greater detail and discuss when you would choose to use one approach over the other.

By the end of all this, you will have a good understanding of the pros and cons of each approach so that you can do the right thing with the JavaScript in your web pages and applications.

Approach #1: All the Code Lives in Your HTML Document

The first approach we will look at is one that we've been using all along so far. This is the approach where all of your JavaScript lives inside a script tag alongside the rest of your HTML document:

<!DOCTYPE html>
<html>
<body>
<h1>Example</h2>

<script>
function showDistance(speed, time) {
    alert(speed * time);
}
  
showDistance(10, 5);
showDistance(85, 1.5);
showDistance(12, 9);
showDistance(42, 21);
</script>
</body>
</html>

When your browser loads the page, it goes through and parses every line of HTML from top to bottom. When it hits the script tag, it will go ahead and execute all the lines of JavaScript as well. Once it has finished executing your code, it will continue to parse the rest of your document.

Approach #2: The Code Lives in a Separate File

The second approach is one where your main HTML document doesn't contain any JavaScript content. Instead, all of your JavaScript lives in a separate document. There are two parts to this approach. The first part deals with the JavaScript file. The second part deals with referencing this JavaScript file in the HTML. Let's look at both of these parts in greater detail.

The JavaScript File

Key to making this approach work is the separate file that contains your JavaScript code. It doesn't matter what you name this file, but its extension must be .js. For example, my JavaScript file is called example.js:

hi everybody!!!

Inside this file, the only thing you will have is JavaScript:

function showDistance(speed, time) {
    alert(speed * time);
}
  
showDistance(10, 5);
showDistance(85, 1.5);
showDistance(12, 9);
showDistance(42, 21);

Everything you would normally put inside a script tag in the HTML will go here. Nothing else will go into this file. Putting anything else like arbitrary pieces of HTML and CSS isn't allowed, and your browser will complain.

Referencing the JavaScript File

Once you have your JavaScript file created, the second (and final) step is to reference it in the HTML page. This is handled by your script tag. More specifically, it is handled by your script tag's src attribute that points to the location of your JavaScript file:

<!DOCTYPE html>
<html>
<body>
<h1>Example</h2>

<script src="example.js"></script> 
</body>
</html>

In this example, if your JavaScript file is located in the same directory as your HTML, you can use a relative path and just reference the file name directly. If your JavaScript file lives in another folder, you should alter your path accordingly:

<!DOCTYPE html>
<html>
<body>
<h1>Example</h2>

<script src="/some/other/folder/example.js"></script> 
</body>
</html>

In this case, our script file is nested inside three folders with the name some, other, and folder. You can completely avoid relative paths and use an absolute path if you want:

<!DOCTYPE html>
<html>
<body>
<h1>Example</h2>

<script src="//www.kirupa.com/js/example.js"></script> 
</body>
</html>

Either a relative path or absolute path will work just fine. For situations where the path between your HTML page and the script you are referencing your will vary (such as inside a template, a server-side include, a 3rd party library, etc.), you'll be safer using an absolute path.

Scripts, Parsing, and Location in Document

A few sections earlier, I briefly described how scripts get executed. Your browser parses your HTML page starting at the top and then moves down line by line. When a script tag gets hit, your browser starts executing the code that is contained inside the script tag. This execution is also done line-by-line starting at the top. Everything else that your page might be doing takes a backseat while the execution is going on. If the script tag references an external JavaScript file, your browser first downloads the external file before starting to execute its contents.

This behavior where your browser linearly parses your document has some interesting side effects that affect where in your document you want to place your script tags. Technically, your script tag can live anywhere in your HTML document. There is a preferred place you should specify your scripts, though. Because of how your browser parses the page and blocks everything while your scripts are executing, you want to place your script tags towards the bottom of your HTML document after all of your HTML elements.

If your script tag is towards the top of your document, your browser will block everything else while the script is running. This could result in users seeing a partially loaded and unresponsive HTML page if you are downloading a large script file or executing a script that is taking a long time to complete. Unless you really have a good need to force your JavaScript to run before your full document is parsed, ensure your script tags appear towards the end of your document as shown in almost all of the earlier examples. There is one other advantage to placing your scripts at the bottom of your page, but I will explain that much later when talking about the DOM and what happens during a page load.

So...Which Approach to Use?

You have two main approaches around where your code should live:

your code contains everything

The approach you end up choosing depends on your answer to the following question: Is the identical code going to be used across multiple HTML documents?

Yes, my code will be used on multiple documents!

If the answer is yes, then you probably want to put the code in an external file and then reference it across all of the HTML pages you want it executing in. The first reason you want to do this is to avoid having code repeated across multiple pages:

many stuff (or schtuff?)

Duplicates make maintenance a nightmare where a change to your script will require you updating every single HTML document with the exact change. If you are employing some sort of templating or SSI logic where there is only one HTML fragment containing your script, then the maintenance issue is less of a problem.

The second reason has to do with file size. When you have your script duplicated across many HTML pages, each time a user loads one of those HTML pages, they are downloading your script all over again. This is less of a problem for smaller scripts, but once you have more than a few hundred lines of code, the size starts adding up.

When you factor all our code into a single file, you don't have the issues I just outlined:

the solution

Your code is easily maintainable because you update your code inside the one file only. Any HTML document that references this JavaScript file automatically gets the most recent version when it loads. By having all of your code in one file, your browser will download the code only once and deliver the cached version of the file on subsequent accesses.

No, my code is used only once on a single HTML document!

If you answered no to the earlier question around whether your code is going to be used on multiple HTML documents, then you can do whatever you want. You can still choose to put your code into a separate file and reference it in your HTML document, but the benefits of doing that are less than what you saw earlier with my example involving many documents.

Placing your code entirely inside your HTML document is also fine for this situation. Most of the examples you will see in this site have all of the code within the HTML document itself. Our examples aren't really going to be used across multiple pages, and they aren't going to be so large where readability is improved by putting all of the code in a separate location.

Conclusion

As you can see, even something as seemingly simple as determining where your code should live ends up taking many pages of overview and discussion. Welcome to the world of HTML and JavaScript where nothing is really black and white. Anyway, getting back to the point of this article, a typical HTML document will contain many script files loaded from an external location. Some of those files you will own. Some of those files will be created by a 3rd party and included into your document.

Also, do you remember the hybrid approach I showed at the very beginning where your HTML document contains both a reference to a separate JavaScript file as well as actual code within the document? Well, that approach is pretty common as well. Ultimately, the approach you end up using is entirely up to you. Hopefully, this tutorial gave you all of the information needed to make the right choice.

Getting Help

If you have questions, need some assistance on this topic, or just want to chat - post in the comments below or drop by our friendly forums (where you have a lot more formatting options) and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly via e-mail, facebook, or twitter.

Brought to you by...

Kirupa Chinnathambi
I like to talk a lot - A WHOLE LOT. When I'm not talking, I've been known to write the occasional English word. You can learn more about me by going here.

Add Your Comment (or post on the Forums)

blog comments powered by Disqus

Awesome and high-performance web hosting!
BACK TO TOP
new books - yay!!!