JS Script Tag

JavaScript

In this tutorial we will learn about script tag.

script tag

We use the script tag to tell the browser the starting and ending point of a script inside the HTML document.

In the following example we have created a script tag and set the value of the type attribute to text/javascript and written some code.

<script type="text/javascript">
	console.log("Hello World");
</script>

JavaScript is the default scripting language for HTML and hence in new browsers we don't have to use the type attribute. But for older browsers we have to set the type attribute.

We can also use the script tag to include an external javascript file into the HTML document.

In the following example we have created a script tag and set the value of the src attribute to the javascript file path /path/to/the/file/app.js.

<script type="text/javascript" src="/path/to/the/file/app.js"></script>

noscript tag

We use the noscript tag to provide alternative content if javascript is turned off in a browser.

In the following example we are using the noscript tag.

<script type="text/javascript">
	console.log("Hello World");
</script>
<noscript>
	No JavaScript
</noscript>

Hello World in console

In the following example we are going to use the console.log() method to print the famous "Hello World!" text in our browser console.

Open your favourite text editor or IDE and create a html file and name it helloworld.html.

Now inside this file write the following HTML.

<!DOCTYPE html>
<html>
    <head>
        <title>Hello World</title>
    </head>
    <body>
        <script type="text/javascript">

        	console.log("Hello World!");

        </script>
    </body>
</html>

Now open the helloworld.html file in the browser and open Console.

Chrome: View -> Developer -> Developer Tools

Firefox: Tools -> Web Developers -> Web Console

Safari: Developer -> Show Error Console

Or, simply right click on the page and select Inspect / Inspect Element and then click on the Console tab.

Once you are in the Console tab you will see the following output.

External JS file

Similarly, we can create a javascript file (say helloworld.js) and write the following code inside.

console.log("Hello World!");

And then include the js file inside the helloworld.html file using the script tag. And when the html file will be opened in the browser it will give us the same result.