Where should I place JavaScript in an HTML file?

JavascriptWeb DevelopmentFront End Technology

JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script>. To place JavaScript in an HTML file, use the <script>…</script> tag.

You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags. 

The <script> tag alerts the browser program to start interpreting all the text between these tags as a script. A simple syntax of your JavaScript will appear as follows:

<script ...>
   JavaScript code

Let us take a sample example to print out "Hello World". We added an optional HTML comment that surrounds our JavaScript code.

The comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so we add that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code. Next, we call a function document.write, which writes a string into our HTML document.

This function can be used to write text, HTML, or both. Take a look at the following code.

            document.write("Hello World!")

Published on 09-Jan-2018 15:21:46