Wednesday, January 4, 2012

Where to place Javascript in HTML web page

Javascript can be placed in <head> or <body>. It can be Javascript code in HTML file, in-between <script> and </script>. Or link to external javascript file using src attribute.

  • Place Javascript code in <head>. It will be executed as long as the browser parses the head; before the page body loaded.
    <!doctype html>
    <head>
    <title>Mobile-Web-App: Test Javascript</title>
    <meta charset="utf-8">

    <!-- Place Javascript code in <head> -->

    <!-- Place Javascript code here directly -->
    <script>
    alert("Hello All:) - It's Javascript in <head>.");
    </script>

    <!-- Link to external Javascript -->
    <script src="extJavascript.js">
    </script>

    </head>
    <body>
    <h1>Mobile-Web-App: Test Javascript</h1>
    <p>Where to add Javascript in HTML: in <head></p>

    </body>
    </html>

    Place Javascript in head
    Place Javascript in head, link to external .js file

  • Place Javascript code in <body>.
    <!doctype html>
    <head>
    <title>Mobile-Web-App: Test Javascript</title>
    <meta charset="utf-8">
    </head>
    <body>
    <h1>Mobile-Web-App: Test Javascript</h1>
    <p>Where to add Javascript in HTML: in <body></p>

    <!-- Place Javascript code in <body> -->

    <!-- Place Javascript code here directly -->
    <script>
    alert("Hello All:) - It's Javascript in <body>.");
    </script>

    <!-- Link to external Javascript -->
    <script src="extJavascript.js">
    </script>

    </body>
    </html>

    Place Javascript in body


extJavascript.js
alert("Alert from External Javascript");




No comments:

Post a Comment