Javascript Pattern

In this article, you will learn how to integrate javascript code in html document. There are two ways to include javascript.

Embed the javascript code directly in the document.

In this process, we have directly written the javascript code in document within script tags. We should avoid this process because the best coding practice is to write the script code in a separate file.

<html>
<head>
<title>Web Page Title.</title>
</head>
<body>
<script>
	alert('hello world');
</script>
</body>
</html>
    

Include javascript external file in the document.

In the given example, we have included external javascript file 'demo.js' in a document.

<script type="text/javascript" src="demo.js">        

We can also include the file from the external server -

<script type="text/javascript"  src="https://www.test.com/demo.js">

It is considered best to write javascript code in the external file because the maintenance of the code becomes easy if written in the external file.

We can place script code in both <head> element and <body> element.

Place Javascript code within the HEAD section

When we place Javascript code in the head section, then all javascript code downloaded and interpreted first before rendering the body tag content. This may slow the content loading time in case, we have included large javascript files.

<html>
<head>
<title>Web Page title is to written here.</title>
<script>
alert('hello world');
</script>
</head>
<body>
	
</body>
</html>
    

Place Javascript code within the BODY section

All the contents within the body section will render first on the webpage and after that javascript code downloaded and interpreted.

<html>
<head>
</head>
<body>
<script>
alert('hello world');
</script>
</body>
</html>
    


These are the attributes of script element

type attribute

This attribute is optional, it has only one the value i.e. 'text/javascript'.

<script type="text/javascript">
</script>

src attribute

The src attribute is used to add an external javascript file.

<script type="text/javascript" src="demo.js" >
</script>

async attribute

This is a boolean attribute of the script element and used for external script file. When webpage load, it downloads the script asynchronously without delaying the page load. This is also an optional attribute.

<script type="text/javascript" async src="demo.js">    




Read more articles


General Knowledge



Learn Popular Language