Creating Javascript in webpages
You can use Javascript in an HTML document in two ways:
- Embedded in the HTML file by putting the code inside one or more
<script>tags; - Using an external Javascript code file and loading that using a
<script src="">tag.
Embedding Javascript in HTML
The <script> tag is an extension to HTML that can enclose any kind of script the browser can executes. A document can have multiple script tags, and each can enclose any number of (Java)script statements.
In the listing below you see a simple HTML file with embedded Javascript. Create a new, empty, Webpage. Copy (or type) the Javascript and HTML code as shown in the listing into the file, save the page and open it in a web browser: It should display the following in the browser:
Here is some normal, static HTML content...
This is scripted content!
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>A Simple Scripted Page</title> </head> <body> <p>Here is some normal, static HTML content...</p> <p> <script> document.write("This is scripted content!"); </script> </p> </body> </html> |
Notice that there is no difference in appearance between the second line, generated with Javascript, and the first line, generated with plain HTML. On the client-side, in the browser output, the user does not see if output was generated by HTML or by Javascript.
Using an external Javascript code file
Rather than embedding the Javascript in the HTML, the src= attribute of the <script> tag lets you specify an external file as source of the Javascript source. For example with the HTML <script src="common.js"></script> you tell the browser to load javascript from the file common.js.
This is especially useful for sharing the same Javascript code among many different pages. Note the ending </script> tag is necessary to create a valid HTML script object!
The SRC attribute can specify any URL, relative or absolute. For example
src="http://www.mysite.com/functions/jsfuncs.js" will load code from a totally different server.
External Javascript files cannot contain any HTML tags: they must contain only Javascript statements! External Javascript file names must have the .js file name suffix.
Open a new empty file. Put the Javascript (only the script itself, not the HTML!) you made in step 1 into this file (you can use copy and paste) and save this file. Make sure it's saved using a .js suffix! Change the Web Page you made in step 1, so that it calls the Javascript from a code file, instead of having the code embedded.

