This tutorial focuses on:
- Declaring a script within a webpage
- Declaring a script in an external file
- Printing text on a webpage
- Including HTML tags in a script
- Including comments in a script
Declaring a script within a webpage
A script can be placed in the head section or the body section of a webpage, but a script will be executed differently depending on where it is placed.
A script placed in the head section of a webpage
A script placed in the head section of a webpage will be executed when it is called, or when certain events are triggered such as the clicking of a button or when a form is submitted.
A script placed in the body section of a webpage
A script placed in the body section of a webpage will be executed when the page loads. A script placed in the body section of a webpage generates the content of the page.
You can have as many scripts on a webpage as you want, this includes both scripts in the head section and the body section of a webpage.
Declaring a script in an external file
An external file in which a script is declared should have a .js extension. This file will be included within the source code of a webpage. An external script is called by the <script> tag using its src attribute. The advantage to using external scripts is that you can include the same script(s) on several pages without having to rewrite them.
In this example, the <script> tag calls the external script named script1.js.
NOTE: External scripts cannot contain the <script> tag!
Printing text on a webpage
Printing text on a webpage is accomplished with the document.write() command.
Including HTML tags in a script
HTML tags can be included in a script using the document.write() command mentioned above. Any tags included in a script with this command will be interpreted by the web browser as regular HTML.
Including comments in a script
There are older browsers still in use that do not recognize the <script> tag and consequently will not be able to execute scripts. In such a case, the content inside the <script> tag will be displayed on the page as regular text. To prevent this from happening, the content of a script can be placed within comment tags. In such a case, older browsers that do not recognize the <script> tag will ignore the script and the content inside the <script> tag will not be displayed on the page. Browsers that can execute scripts will ignore the comments and execute the script anyway.