Pages - Menu

Tuesday, December 27, 2016

JavaScript Where To

The <script> Tag
JavaScript code must be written between <script> and </script> tags.
example
      <script ...>
           JavaScript Code
     </script>
Note: 
Old JavaScript examples may use a type attribute: <script type="text/javascript">. The type Attribute is not necessary. JavaScript is the default scripting language in HTML.

Where to Write JavaScript in <head> or <body>
you can write or place any number of scripts in an HTML document. 
You can write or place scripts in the <head>, or in the <body> section of an HTML page, or in both.

JavaScript in <head>
In below example, a JavaScript function is written in the <head> section of an HTML page.
This function will be called when a button is clicked.

example

<!DOCTYPE html>
<html>
<head>
<script>
function myFirstFunction() {    document.getElementById("demo").innerHTML = "New Paragraph.";
}
</script>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFirstFunction()">Test it</button>
</body>
</html>

JavaScript in <body>

In below example, a JavaScript function is written in the <body> section of an HTML page.
This function will be called when a button is clicked.

example

<!DOCTYPE html>
<html>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFirstFunction()">Test it</button>
<script>
function myFirstFunction() {
   document.getElementById("demo").innerHTML = "New Paragraph.";
}
</script>
</body>
</html>

External JavaScript

You can also write or place the scripts in external files.

External file: myFirstScript.js
function myFirstFunction() {         document.getElementById("demo").innerHTML = "New Paragraph.";
      }

It's better to use the external JavaScript when the same code is used in many web pages. 
To use the external script, mention the name of the script file in the src attribute of a <script> tag.
JavaScript files have the .js extension.
You can place an external script reference in <head> or <body> or both.
example

<!DOCTYPE html>
<html>
<body>
<script src="myFirstScript.js"></script>
</body>
</html>

External References

External scripts can be referenced with full URL or with a physical path relative to the current webpage.

example 1
This below example uses a full URL to link with a external script
<script src="http://www.techspeculum.com/myFirstScript.js"></script>

example 2
This example uses a file with physical path which is located in the specified folder on the current website.
<script src="/javascript/myFirstScript.js"></script>

Advantages of External JavaScript

Below are the advantages of placing scripts in external files.

  • It allows to separate HTML and code.
  • It Can speedup page loads through cached JavaScript files.
  • It helps to read and maintain the HTML and JavaScript easily.


No comments:

Post a Comment