How to Enter JavaScript Using a URL (href:="javascript:")

How to Enter JavaScript Using a URL (href:="javascript:")



The last way (and also the least used today) is to insert JavaScript into the href address of the HTML tag. This method is also known as the javascript protocol. It is called so, because we change the link address from the usual http// protocol: to javascript:


As an example of its use, consider the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8" />
<head>
<title>Belajar JavaScript di Duniailkom</title>
</head>
 
<body>
<h1>Belajar JavaScript</h1>
<p>Saya sedang belajar JavaScript di duniailkom.com</p>
<p>Belajar Web Programming di Duniailkom.</p>
 
<a href="javascript:alert('Hello World!!')">
Hallo Dunia...</a>
 
</body>
</html>


If you run the code above, and click on the Hello World… link, an alert Hello World!! will appear, which comes from JavaScript. Here we have run JavaScript using the javascript protocol.

This way of running JavaScript dates back to the early days of javascript, and has been abandoned a lot.


Best Practice JavaScript: use the <script src="”> . tag

Of the 4 ways to input JavaScript code, separating the JavaScript code into a separate file (using the <script src="”> method) is the most recommended. Some of the advantages of using the <script src> method when compared to other methods of inserting JavaScript are:


Simplify HTML pages by removing all JavaScript code, so that HTML pages contain only content.

An external JavaScript file can be used for multiple HTML pages, so if changes are needed, we only need to edit a file instead of changing one HTML page where the JavaScript is written internally.

If an external JavaScript file is used by multiple pages, it only needs to be downloaded by the web browser the first time. At the time of loading other pages, the web browser simply takes it from the browser cache, thus speeding up page loading.

In this javascript tutorial we have learned 4 ways to input or insert javascript into HTML. If you notice, from the existing examples, I 'put' the javascript code at the top of the HTML (precisely in the <head> tag). However, JavaScript should not be placed in this section.


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

Post a Comment

Previous Post Next Post