JavaScript

External Javascript Example

HTML, CSS and Javascript are the programming power team that have been used together since virtually forever, so it’s only logical to think that they can be included into one another in a multitude of ways.

As much as I agree that HTML & CSS have a very special connection, to the point that it’s very difficult to even imagine one without the other, Javascript & HTML have a dependency on each other which is just as strong.

How can you use external Javascript files into an HTML document? Let’s see!
 
 

1. Ways to insert Javascript into HTML

There are a number of ways in which you can interweave Javascript and HTML in your work. There are four methods which are the most used and widespread among programmers, three of which place the Javascript part of your code inside the HTML document and the last one by using external files which contain all your Javascript code. These methods are:

  1. Inside the <head> tag
  2. Inside the <body> tag
  3. Inside both the <head> tag and the <body> tag
  4. Using External Javascript

Let’s take a look at each one of them separately!

2. Javascript code inside the HTML document

Before explaining the placing of the script inside the HTML document, you need to understand how the rendering of the page is done by the browser, and that is fairly easy. The browser firstly displays an empty document, and starts “filling it up” according to the code it encounters in the HTML document. That means that first the <head> is displayed, with the title and all the rest, and then we start working on the <body>. The general rule is to start rendering from the top to the bottom: If the browser encounters headings or paragraphs it displays them, and say we have placed a script in the middle of the document. The browser will run this script, and only after it’s done completely will it start displaying the rest of the document.

Of course there are advantages and disadvantages of using these three methods, the main being the simplicity in understanding for codes that aren’t too long. How can we use them in real life? See below!

2.1 Javascript inside the <head> tag

If you have decided to place your Javascript code inside the HTML document, deciding where exactly in it to put it is just a matter of convenience. If you need your script to run first things before loading anything else, then it’s better to put it in the <head> part of the document. Take a look at the example below:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>External JS</title>
    <script>
    for(var i=1; i<=5; i++) {
      alert("Alert" + i)
    }
    </script>

</head>
<body>

<h1>Display five alerts first </h1>

<h1>Continue rendering the rest of the document.</h1>

</body>
</html>

Our example is pretty simple: We have a Javascript code snippet that gives out 5 alerts before continuing with the rest of the document. In this case we have placed the script in the head of the document, encapsulated by <script> tags. As you can see, you will first have to click OK after each of the alerts for the browser to render the rest of the page.

2.2 Javascript inside the <body> tag

You can always place your JS piece of code in the <body> part of the document, and a very popular choice about it would be the very end of this part. This is because the script would be the last thing to be executed, because the user wouldn’t be obligated to wait for any scripts to load in order to see his webpage rendered. The downside, of course, and a major one at that would be the fact that while the page would have all it’s elements rendered before the scripts, they wouldn’t all be functional before the scripts have all loaded fully. The example above, would look slightly differently now:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>External JS</title>
</head>
<body>

<h1>Display five alerts first </h1>

<script>
    for(var i=1; i<=5; i++) {
      alert("Alert" + i)
    }
</script>

</body>
</html>

As you see, we have only altered the position of the <script> tags. However, because of the rendering rule we mentioned, the heading you see will be displayed before there are any alerts put out. Suppose we have another heading after the script? It would be invisible until all the script has finished it’s execution. Say we have an infinite loop and the script never stops? That’s a hazard and should be avoided! Even in other ways of implementing JS and HTML together (unless you’re aiming for that effect).

2.3 Javascript inside both the <head> tag and the <body> tag

By now, it’s not hard to understand that you can even divide your Javascript code into parts and place them wherever you feel they would increase your web application’s functionality and UX. This may solve the problem posed by placing all your scripts before the ending of the body, as you can place the most urgent parts in the head and the rest of the functionality which do not require the whole page to be loaded can be put in the end of the body of your document, thus lowering the loading time your webpage needs. Neat, right?

3. External Javascript

In most cases your web app contains more than one page, and more than one of the functionalities will be repeated in each one of them. One course of action could be to copy and paste the relevant code into each page’s respective HTML file. However, that would be not only time consuming, but also would take up space and be annoying to boot. So what can we do except for this?

In this case, the best thing to do would be to create a file where you put only your Javascript code, and call it any time you need it to. Note that no Javascript code would be written in your HTML file at all. So how to go about it? There are two important things to do:

  1. Creating the JS file
  2. Calling the JS file

3.1 Creating the Javascript File

It is a pretty simple procedure allowing you to create a Javascript file to save all of your script. First of all you have to open a text editor of your choice (MS Word, Notepad, Notepad++ etc.) and place there all of your Javascript code, without any tags, not even the <script> ones. Your entire file should look like below:

external.js

for(var i=1; i<=5; i++) {
      alert("Alert" + i)
    }

As you see, there is no file structure, no tags, nothing except plain simple JS code. Of course you can add as much JS code as you wish to.

After doing this, you just have to save this file by giving it a name of your choice and the extension .js. Do NOT forget the extension, it’s very important in letting your browser (and not only) know what type of file this one is. And with this, we’re done with the first step.

3.2 Calling the Javascript File

Even though you created you Javascript file (or downloaded the library of your choice), without it being called into the HTML document where you want that code executed, it would have been pointless. So how can you call it? Easy!

Remember those <script> tags we completely sidestepped when we created the JS file? They will come in handy now. By keeping in mind the rendering rule you can place your empty script tags wherever you need them. After doing that you will have to add two attributes to the opening tag: src and type.

The first attribute, src, will be the source where the browser can find the file. In other words it’s the relative path to the file, starting from your current location. The second attribute, type, will contain the type of the file you are including in your HTML document. In our case, it’s value should be text/javascript. You can do this by adding the code below where you deem fit:

index.html

<script src="js/external.js" type="text/javascript"></script>

There are some things to note here, the first one being that external.js is the name of the Javascript file in our case, as you might have noticed before. The second thing to note is that by adding the src attribute, you have automatically told the browser to ignore the contents of the tag. However, that doesn’t mean you can make <script> into a self closing tag, you will have to add the closing tag.

Moreover, even though nowadays there are validators to see if your code is correct or not, you may find that sometimes you can use ugly code and it will still (unfortunately) work. One example would be the type attribute, it’s function was done before by the language attribute which is obsolete and not used anymore for Javascript scripts. Another thing would be the “advice” to wrap your script in comment tags. Do NOT do that! The browser will completely ignore your code. It used to work in very very old browsers though, such as Nescape, which i’m willing to bet you (and me too for that matter) didn’t even know existed once upon a time.

And with this you’re all set to go.

4. Download the source code

This was an example of External Javascript.

Download
You can download the full source code of this example here: ExternalJS

Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button