FORUM

Where Should Your Code Live

by kirupa   |   filed under JavaScript 101

Let's take a break from our regularly scheduled...programming (ha!). So far, all of the code we have been writing has been contained fully inside an HTML document:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>An Interesting Title Goes Here</title>

  <style>
    body {
      background-color: #EEE;
    }
    h1 {
      font-family: sans-serif;
      font-size: 36px;
    }
    p {
      font-family: sans-serif;
    }
  </style>
</head>

<body>
  <h1>Are you ready for this?</h1>
  <p>Are you ready for seeing the most amazing dialog you will have ever seen?</p>

  <script>
    alert("hello, world!");
  </script>
</body>

</html>

We are going to take a step back and revisit whether having this arrangement between HTML, CSS, and JS in the same document makes sense for all situations. To simplify how we talk about our document structure, let's replace the code view with a more...um, artistic view...involving some really nicely designed boxes:

javascirpt in document

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

completely separate files

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

The thing to note is that none of these approaches are mutually exclusive. We can mix both approaches into an HTML document and have a hybrid approach where we have both an external JavaScript file as well as lines of JavaScript code fully contained inside the document:

code mixed into a document

To make things more interesting, we 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.

Onwards!

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 our 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 our 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 our code, it will continue to parse the rest of our document. This means the location the script tag lives in our page is important. We will discuss that later when looking at the Running Your Code at the Right Time tutorial.

Approach #2: The Code Lives in a Separate File

The second approach is one where our main HTML document doesn't contain any JavaScript content. Instead, all of our 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 our 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 we 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 our browser will complain.

Referencing the JavaScript File

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

<!DOCTYPE html>
<html>

<body>
  <h1>Example</h2>

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

</html>

In this example, if our JavaScript file is located in the same directory as our HTML, we can use a relative path and just reference the file name directly. If our JavaScript file lives in another folder, we would alter our 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. We can completely avoid relative paths and use an absolute path as well:

<!DOCTYPE html>
<html>

<body>
  <h1>Example</h2>

  <script src="https://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 our HTML page and the script we are referencing will vary (such as inside a template, a server-side include, a 3rd party library, etc.), we'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?

We have two main approaches around where our 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?)

Duplicate code makes 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 the 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 we just saw, even something as seemingly simple as determining where our 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 our HTML document contained 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.

Got a question or just want to chat? Comment below or drop by our forums (they are actually the same thing!) where a bunch of the friendliest people you'll ever run into will be happy to help you out!

When Kirupa isn’t busy writing about himself in 3rd person, he is practicing social distancing…even on his Twitter, Facebook, and LinkedIn profiles.

Hit Subscribe to get cool tips, tricks, selfies, and more personally hand-delivered to your inbox.

COMMENTS

Serving you freshly baked content since 1998!
Killer hosting by (mt) mediatemple

Twitter Youtube Facebook Pinterest Instagram Github