Where and How to ?

JavaScript can be placed in the <body> and the <head> sections of an HTML page. For faster web-page load, it is advised to place "script" tag just before "</body>" tag.

The <script> Tag

In HTML, JavaScript code must be inserted between <script> and </script> tags.

Example

<script>
alert('Hello World');
</script>

 Above example, will bring the pop-up box with message "Hello World".

Older examples may use a type attribute: <script type="text/javascript">.
This type attribute is not required. JavaScript is the default scripting language in HTML.]

 Where to Keep Javascript ? Head or Body

Some people would recommend you to place your all "<script>" tag in your <head> tag, but speaking frankly that is actuall bad idea. To make your webpage load faster or more effectively. It is highly advised to keep your <script> tag right before </body> tag like beolow :-

<!DOCTYPE html>
<html>
<head>
    <title> Javascript Example</title> 
</head>

<body>

    <h1>Javascript Web Page</h1>

    <p id="para">A Paragraph</p>

    <button type="button" onclick="myFunction()">Try it</button>

    <script>
    function myFunction() {
        document.getElementById("demo").innerHTML = "I am added by Javascript.";
    }
    </script>

</body>
</html>

We will talk about "onlick" and other event later on our tutorial.

Note: If any website or person, tells you to place your <script></script> tag inside <head></head> , Don't listen at all. He is an Idiot. It's better to run away from people like him.

Just follow our rule of placing script tag before closing body tag and you will be smarter developer by the end , when you have covered almost all the basics of javascript.

External Javascript

script can also be placed in external file, which is again good idea only if you have lots of script code.

Advantage of External Javascript :

  1. make your page more clean and
  2. helps in faster development purpose.
  3. easier to read and maintain.
  4. cached javascript files can speed up page loads.

Example How to ?

Create a new file "scripts.js" like below :-

function myFunction() {
   document.getElementById("para").innerHTML = "I am added by Javascript.";
}

Now, in your HTML file, just place below syntax , right before </body> tag like below: 

<!DOCTYPE html>
<html>

<head>

    <title>Javascript Webpage</title>
</head>

<body>

    <h1>Javascript Webpage</h1>
    <p id="para">A Paragraph</p>


    <script src="myScript.js"></script>
</body>
</html>

Remember :  External scripts cannot contain <script> tags.


Loading ...

Related Results :

  1. Where and How to ?
Note :
  • Related Posts are generally User Blog posts.
  • or Other tutorials from other networks of w3clan.com.
  • Any registered user can create related posts based on search term tags.

About the Author