HTML Script

The script element is used to embed or reference JavaScript within an HTML document to add interactivity or affect the behavior of web pages.

Client-side Scripting

Client-side scripting refers to the type of computer programs that are executed by the user's web browser. JavaScript is the most popular client-side scripting language on the web.

Common uses for JavaScript are form validation, generate a pop-up alert box message, creating image gallery, dynamic changes of content, etc.

Adding a Script to HTML Document

The <script> element is used to define a client-side script.

The script in the example below writes Hello World! to the HTML output:

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  •     <meta charset="UTF-8">
  •     <title>Embedded JavaScript Example</title>        
  • </head>
  • <body>
  •     <script type="text/javascript">
  •         document.write("Hello World!");
  •     </script>
  • </body>
  • </html>
 

Tip:Ideally, scripts should be placed at the bottom of the page, because scripts block parallel downloads. That will make your web pages load faster.


Calling an External Script

You can also place your scripts into a separate file, and then call that file through the src attribute in your HTML document. This is useful if you want the same scripts available to multiple documents — it saves you from repeating the same task over and over again, and makes your website much easier to maintain.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  •     <meta charset="UTF-8">
  •     <title>External JavaScript Example</title>        
  • </head>
  • <body>
  •     <script type="text/javascript" src="hello.js"></script>
  • </body>
  • </html>

The HTML noscript Element

The <noscript> element is used to provide an alternate content for users that have either disabled scripts in their browser or have a browser that doesn't support client-side scripting.

The noscript element can contain all the HTML elements that you'd include inside the <body> element of a normal HTML page.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  •     <meta charset="UTF-8">
  •     <title>No-script Example</title>        
  • </head>
  • <body>
  •     <script type="text/javascript">
  •         document.write("Hello World!");
  •     </script>
  •     <noscript>
  •         <p>Sorry, your browser does not support JavaScript!</p>
  •     </noscript>
  • </body>
  • </html>
 

Note:The content inside the noscript element will only be displayed if scripts are not supported, or are disabled in the user's browser.

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.