script tags in client side javaScript

Script tags come into play with web development when I want to do anything that involves the use of client side javaScript in a website. In this post I will be sharing all the little things there are to know about when working with script tags to get things working with client side javaScript.

1 - script tags can be used to add in line javaScript code to a website

A script tag can be used to add javaScript to a website by placing the javaScript code between the beginning and ending script tags.

1
2
3
4
5
6
7
8
9
10
11
<html>
<head>
<title>script tags and inline scripting</title>
</head>
<body>
<script>
var n = 40;
console.log(n+2); // 42
</script>
</body>
</html>

2 - script tags and external javaScript files

It is also possible to load external scripts as well. This can be done by making use of the src attribute of the script tag to point to the url of the external javaScript file.

For example here I have some html, and I am linking to the external javaScript file by adding a script tag in the body element just before the end body tag.

1
2
3
4
5
6
7
8
9
10
11
12
<html>
<head>
<title>script tag</title>
</head>
<body>
<script>
</script>
<div id="out"></div>
<script src="main.js"></script>
</body>
</html>

I then have this javaScript in the external file that just grabs the div tag with and id of out and just adds some text to that element.

1
document.getElementById('out').innerText = 'external';