Sunday, 24 July 2016

Using JavaScript in HTML Document

We can insert JavaScript  code in html document using script element. The script element either contains scripting statement or reference to a external script file.

Attributes of the Script Element

  • async - specifies whether the script should be executed asynchronously or not.
  • type - specifies multipurpose internet mail extensions type of script.
  • charset - specifies the character encoding used in the script.
  • defer - specified whether the browser will continue parsing or not.
  • src - specifies the uniform resource locator of the file that contains the script.
Script element can be used in the web page in the following ways
  • In the Head element
  • In the Body element
  • In the external script file
JavaScript in the Head Element
We can place script inside the head element. Script present in the head element runs, when some action is performed such as click of the submit button.
Example

<!DOCTYPE html>
<html>
<head>
    <title>Script Inside Head element</title>
    <h1>Script Inside Head element</h1>
    <script >
        document.write("Welcome to the JavaScript");
    </script>
</head>
</html>



JavaScript in the Body Element
We can place script inside the body element. Script present in body element runs, when page starts loading in a web browser.
Example

<!DOCTYPE html>
<html>
<head>
    <title>Script Inside Body element</title>
</head>
<body>
    <h1>Script Inside Body element</h1>
    <script>
        document.write("Welcome to the JavaScript");
    </script>
</body>
</html>


JavaScript in the External file
We can place javaScript code in the external file if code is very lengthy, It affects the readability of the the html document. We can also reuse the javascript in several pages by including the external file.
Javascript file are saved with the extension .js.
Example
Create External.js file and put this code
document.write("Script In External File");

In HTML file
<!DOCTYPE html>
<html>
<head>
    <title>Script in External File</title>
    <script src="Externaljs.js"></script>
</head>
<body>
    <h1>Script Inside External File</h1>
</body>
</html>


0 comments:

Post a Comment