How to Enter JavaScript Using (external JavaScript)

How to Enter JavaScript Using the <script src=" "> tag (external JavaScript)



The second way or method to input JavaScript code into an HTML page is to move the JavaScript code into a separate file, then 'call' it from the HTML. This method is highly recommended because it will provide many advantages and flexibility in creating JavaScript programs.

A JavaScript file is saved in a .js extension, such as: Kode.js, register.js, or Kodeku.js. From the HTML page, we call it using the <script> tag with the src attribute. The src attribute contains the address of the javascript file, as follows:

<script src="code_javascript.js"></script>

Note that the <script> tag remains closed with a closing tag </script>, or you can make it a self closing tag like this:

<script src="code_javascript.js" />

Naming JavaScript files with the .js suffix is simply a consensus among programmers. You can make any suffix or extension, such as: Kode_javascript.aku, or Kode_javascript.duniailkom, as long as the <script> tag matches the file name, such as <script src="kode_javascript.duniailkom"></script>

However, to be more comfortable and not confusing, you should still follow the agreement by using the .js suffix.

As an example program, I will display the alert “Hello World!!” like the previous program code, but this time I will separate it into a separate file. The JavaScript code will be moved to the code_javascript.js file with the following file contents:

alert("Hello World!!")

Yes, just that 1 line, and save it in the same folder where the HTML code will be executed with the file name Kode_javascript.js. Then in the HTML program code, we will run the javascript file as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type"
     content="text/html; charset=UTF-8" />
<head>
<title>Belajar JavaScript di Duniailkom</title>
<script src="kode_javascript.js"></script> 
</head>
<body>
<h1>Belajar JavaScript</h1>
<p>Saya sedang belajar JavaScript di duniailkom.com</p>
<p>Belajar Web Programming di Duniailkom.</p>
</body>
</html>

Note that in the code_javascript.js file I immediately wrote the alert command, and it was called by the <script>  tag on the 7th line of the example HTML file above.

For discussion about : 
I will explain in the next article separately






Post a Comment

Previous Post Next Post