Hello World!

Lecture



Hello World!

  1. SCRIPT tag
  2. External scripts

In this article we will create a simple script and see how it works.

SCRIPT tag

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.

External scripts

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
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone