About JavaScript code, examples

About JavaScript code, examples
Rate this post

JavaScript is an interpreted, object-oriented language and is known as the scripting language for web pages.

How to add javascript code in HTML?

In HTML pages, JavaScript code must be placed between <script> and </script> tags.

<script>
alert("Hi webpedia");
</script>

There are old javascript examples that use “type attribute” inside <script> tag like:

<script type="text/javascript">
alert("Hi webpedia");
</script>

The type attribute is not required because JavaScript is the default scripting language in HTML.

Where to place JavaScript code in HTML?

The JavaScript code can be placed inside the <body> or in the <head> section of any HTML page.
To improve page load, is recommended to place the JavaScript code at the bottom of the <body> element, just before </body> tag.

The position of JavaScript code in a page does matter.
By default the code will be executed as soon as the browser sees it.

External JavaScript code

JavaScript code can also be placed in external files. This method brings us some advantages:

  • Use the same code in many different web pages.
  • Separate HTML and JavaScript code.
  • Cache the JavaScript files, which can improve the site speed.
  • Also, the JavaScript code is easier to read.

JavaScript files have the file extension.js and must be placed in <body> or <head>, inside the src (source) attribute of the <script> tags like this:

<script src="myFile.js"></script>

Make sure the external .js files does not contain <script> tags!!!

Leave a Reply

Your email address will not be published. Required fields are marked *