Every script presented in this series has used the <script> tag with the language="JavaScript" attribute. However, you can also use the src attribute to specify an external file that contains the code to be executed. The only stipulation is that the external file be given a .JS extension when it is named. For example, I could place the following code in a file called HELLO.JS:
alert("Hello world!");
I could then create a page called HELLO.HTM to call the code. Assuming that both files were located in the same directory, the code would look like this:
<html> <head> <title>Hello test</title> <script language="JavaScript" src="hello.js"> </script> <body></body> </html> |
Originally, the src attribute was introduced into the language to hide code from users. When you 'view source' of a page with an external script, you can't see the code, and thus can't rip it off. However, I see this as the single greatest drawback to this approach. My first script was a hack job on someone else's code, and it's a great way for beginners to learn the language.