Lecture
In this article we will create a simple script and see how it works.
JavaScript programs can be inserted anywhere in HTML using the SCRIPT tag. For example:
01 |
02 | < html > |
03 | < head > |
04 |
05 | < meta charset = "utf-8" > |
06 | head > |
07 | < body > |
08 |
09 | < p >Начало документа... p > |
10 |
11 |
14 |
15 | < p >...Конец документа p > |
16 |
17 | body > |
18 | html > |
Open code in new window
This example uses the following elements:
The script tag contains executable code. Previous HTML standards required the mandatory indication of the type attribute, but now it is no longer needed. Simply
The browser for which such tricks were intended, a very old Netscape, has long died. Therefore, there is no need for these comments.
If there is a lot of JavaScript code, it is put into a separate file that is connected in HTML:
Here, /path/to/script.js is the absolute path to the file containing the script (from the site root).
The browser itself will download the script and execute it.
For example:
01 | < html > |
02 | < head > |
03 | < meta charset = "utf-8" > |
04 |
05 | head > |
06 |
07 | < body > |
08 |
11 | body > |
12 |
13 | html > |
Open code in new window
The contents of the /files/tutorial/browser/script/rabbits.js file:
1 | function count_rabbits() { |
2 | for ( var i=1; i<=3; i++) { |
3 | alert( "Кролик номер " +i) |
4 | } |
5 | } |
Open code in new window
You can also specify the full URL, for example:
You can also use the path relative to the current page, for example src="script.js" if the script is in the same directory as the page.
To connect multiple scripts, use multiple tags:
... |
As a rule, only the simplest scripts are written in HTML, and complex ones are put into a separate file.
Thanks to this, the same script, for example, a menu or a library of functions, can be used on different pages.
The browser will only download it for the first time and, if the server is properly configured, it will be taken from its cache.
If the src attribute is specified, the contents of the tag are ignored.
In one SCRIPT tag it is impossible to simultaneously connect an external script and specify the code.
That's not how it works:
You need to choose: either SCRIPT comes with src , or contains code. The tag above should be broken down into two: one with src , the other with code:
show clean source in a new windowHide / show line numbers for code printing with backlight preservation
1 |
2 |
Comments
To leave a comment
Scripting client side JavaScript, jqvery, BackBone
Terms: Scripting client side JavaScript, jqvery, BackBone