Where to put JavaScript in an HTML Document ?

Scripts can be placed inside the body or the head section of an HTML page or inside both the head and body. We can also place javascript outside the HTML file which can be linked by specifying its source in the script tag.

JavaScript in head: A JavaScript function is placed inside the head section of an HTML page and the function is invoked when a button is clicked. 

Examples: 




<html>
    <head>
        <script>
            function gfg() {
            document.getElementById("demo").innerHTML = "Geeks For Geeks";
            }
        </script>
    </head>
    <h2>
        JavaScript in Head
    </h2>
    <p id="demo"
       style="color:green;">
        geeksforgeeks.
    </p>
    <button type="button"
            onclick="gfg()">
        click it
    </button>
</html>

Output: 



 

JavaScript in body: A JavaScript function is placed inside the body section of an HTML page and the function is invoked when a button is clicked. Example: 




<html>
    <head>
    </head>
    <body>
        <h2>
            JavaScript in Body
        </h2>
        <p id="demo">
            geeksforgeeks.
        </p>
        <button type="button"
                onclick="gfg()">
            Try it
        </button>
        <script>
            function gfg() {
                document.getElementById("demo").innerHTML = "Geeks For Geeks";
            }
        </script>
    </body>
</html>

Output: 

 

External JavaScript: JavaScript can also be used as external files. JavaScript files have file extension .js . To use an external script put the name of the script file in the src attribute of a script tag. External scripts cannot contain script tags. 

Example:

 Script.js




function gfg () {
    document.getElementById('demo').innerHTML = 'Paragraph Changed'
}

Index.html




<html>
    <head>
    </head>
    <body>
        <h2>
              External JavaScript
        </h2>
        <p id="demo">
            Geeks For Geeks.
        </p>
        <button type="button"
                onclick="myFunction()">
               Try it
        </button>
        <script src="myScript.js"></script>
    </body>
</html>

 Output:

 

Advantages of External JavaScript:


Article Tags :