Вы находитесь на странице: 1из 255

-

OREILLY* Ifxnoof. p r e s s

High Performance

JavaScript
Nicholas Zakas

REILLY*

JavaScript

-'

20J2

JavaScript.
.

.

.
.
.
.
.

JavaScript. . - . . - .: , 2012. - 256 ., .


ISBN 978-5-93286-213-1
-,
JavaScript -
. ,
JavaScript .
,
, .
, , , DOM,
.
, Yahoo!,
-,
JavaScript
,

JavaScript.
,
.
-
JavaScript,
.
ISBN 978-5-93286-213-1
ISBN 978-0-596-80279-0 ()
-, 2012
Authorized Russian translation of the English edition of High Performance JavaScript,
First Edition ISBN 9780596802790 2010 Yahoo!, Inc. This translation is published
and sold by permission of OReilly Media, Inc., the owner of all rights to publish and
sell the same.
,
.
, , .

-. 199034, -, 16 , 7,
. (812) 380-5007, www.symbol.ru. N 000054 25.12.98.
26.06.2012. 70x100 V16*
. 16 . . 2457.
Konica Minolta
, . -, . 1, . 6
.: (495) 926-63-96, www.bukivedi.com.info@ bukivedi.com

- ,
, -


........................................................................................................
1. ................................................................................. 21
...............................................................................22
................................................................................... 24
............................................................26
.................................................................................26
sc rip t................................................................ 27
XMLHttpRequest.............................31
.............................32
......................................................................................................36
2. ............................................................................................. 37
.................................................................. 38
. . . .39
...........................41
............................................. 44
..........................................................46
, ............................................. 47
................................................................................................. 50
................................................................................................... 50
...................................................................................52
....................................................................................... 54
............................................... 55
......................................................................................................57
3. D O M .................................................................................58
DOM ........................................................................ 58
.................................................................... 59
DOM ................................................... 59
innerHTML DOM.............................61
.....................................................................................65
HTML-......................................................................................... 66
DOM ....................................................................................... 71

............................................................75
?........................................................75
. . . . 76

.......................................................................................78
............................................. 81

............................................................................ 82
IE :hover..................................................................................................... 82
................................................................83
..................................................................................................... 85
4. .............................. 87
.................................................................................................................. 87
................................................................................................. 88
...................................................................... 89
..................................................................94
.......................................................................................95
if-else sw itch.......................................................................... 95
if- e ls e ............................................................97
.....................................................................................99
............................................................................................................ 101
................................................101
............................................................ 103
......................................................................................................104
................................................................................................105
....................................................................................................108
5. ..........................................................109
....................................................................................... 110
(+) - (+ = )..................................................110
.................................................................... 113
String.prototype.concat()...........................................................................115
......................................................116
..................................................117
......................................................................................................118
.............................................................................121
.................................127

...........................................................................127
.................. 131
................................................................................................. 132
.............................132
.......................... 135
.................................................................................136

....................................................................................................138
6. ...........................................................................139
................ 139
............................................................................. 141
- ?.................................................................143
............................................................................... 145
....................................................................................... 145
....................................................................................... 148
........................................... 148
....................................................................................... 150
................................. 152
.............................................................. 154
.......................................................................155
........................................... 155
........................ 156
.......................................................................157
................................................................ 157
....................................................................................................159
7. A jax...................................................................................................................... 160
............................................................................................. 160
............................................................................................161
....................................................................................... 168
..............................................................................................171
XM L.............................................................................................................. 171
JSON.............................................................................................................. 175
HTML............................................................................................................ 179
............................................................ 181
...................................184
Ajax...................... 185
...............................................................................185
Ajax........................ 188
................................................................................................... 189
8. .....................................................................191
..............................................191
/......................................... 193
...................................194
...............................................................................195
................................................... 196
.................................................................. 197
...................................................................................197
.................................................................................. 200
................................................................................................... 202

10

9.
JavaScript .............................................................................. 203
Apache A n t ....................................................................................................... 204
JavaScript-..................................................................205
JavaScript-...................................... 206
JavaScript-............................................................. 209
.................. 211
JavaScript-...................................................................... 211
JavaScript-................................................................213
, .......................................214
.............................. 215
JavaScript-pecypcoB............................................................215
JavaScript-............................................... 216
................................................................................................... 218
10. ................................................................................................. 219
JavaScript-..................................................... 220
YUI P ro filer......................................................................................................221
.....................................................................................225
F ireb u g ..............................................................................................................226
..................................................... 227
........................................................... 228
N e t ................................................................................................. 229
Internet Explorer .................................... 230
- S a fa ri..................................................................233
Profiles...........................................................................................233
Resources.......................................................................................236
Chrome....................................................... 237
.............................. 238
Page Speed......................................................................................................... 239
Fiddler................................................................................................................ 241
YSlow..................................................................................................................243
dynaTrace Ajax Edition.................................................................................. 245
................................................................................................... 248
.................................................................................. 249


1996 Netscape Navigator
JavaScript, .
,
. -


. -,
, .
JavaScript
-.
, ,
, JavaScript
.
. ,
, , 30-60 ,
, , -
. , Java
Script .



. , ,
.
,
.
-
.


. , JavaScript.
, ,
, .
, JavaScript,
, ,
. Internet Explorer 4 HTML (-

12

)
, JavaScript
.

(Document Object Model, DOM),
HTML, In
ternet Explorer 5, Netscape 6 Opera.
-262.
, DOM ( )
JavaScript, -.
API,
JavaScript, JavaScript,
, .


-
JavaScript
JavaScript, 1996
.
JavaScript ,

JavaScript.
Internet Explorer 6,
,
- - .
, IE6 ,
, . -, 2001 ,
IE6,
JavaScript, , 2005 .

JavaScript IE6,
. ,
,
. - ,
,
.
: - ,
JavaScript .

,
.

, -
.

13

,
.
,
,
. ,
, ,
.

, .
JavaScript
,
.


JavaScript

JavaScript 2008 . Google ,
Chrome. ,
JavaScript
V8. JavaScript V8
(Just-In-Time, JIT),
JavaScript
.
JavaScript.

Java
Script. Safari 4 JIT- JavaScript
Squirrel Fish Extreme ( Nitro),
a Firefox 3.5 - TraceMonkey,
.
JavaScript
, . -

. .




, JavaScript ,
. ,

, ,

14

. ,
, ,
, -
-
.
JavaScript
,

.
, ,
JavaScript,
, , DOM,
. ,
(ECMAScript),
JavaScript,
.

JavaScript
. DOM, ,
, JavaScript .
,

JavaScript.



JavaScript. , 1,
JavaScript-
. 2 -8
,
. 9
JavaScript-
, 10
, ,
.
:
3 DOM, (Stoyan Stefanov)
5 , (Steven
Levithan)
7 Ajax, (Ross Harmes)
9
JavaScript, (Julien Lecomte)
10 , (Matt Sweeney)

15

-,
-.
,
.

JavaScript
1
- JavaScript .
JavaScript
.
,
, .


,

JavaScript.
,
,
.
2 , JavaScript-
. ,
, , ,
, ,
.
3 DOM (Stoyan Stefanov),
-. , -
DOM JavaScript.
, DOM,
,
.
4 ,
,
, ,
. ,
, ,
.
- ,
5
(Steven Levithan),
. -

16

,
,
.
6
. JavaScript-
, .
,
.
7 Ajax (Ross Harmes)
.
,
Ajax
XMLHttpRequest .
8
,
JavaScript.

JavaScript- ,
.

. 9
JavaScript (Julien Lecomte)
,
.
, ,
HTTP .

JavaScript- -
.
(Matt Sweeney)
10 . , JavaScript
,
HTTP,
.


-
JavaScript,
-.

17

,
, .

,
,
, ,
, .

,
.

,
, .
,
.
.


.

.
,
. ,

, .
-

OReilly. ,
.


.
,
.

18

, ISBN. : High Performance


JavaScript, by Nicholas . Zakas. Copyright 2010 Yahoo!, Inc., 978-0-59680279-0.

missions@oreilly.com.

Safari Books Online


^

Safari Books Online - , Booksonline 7500


.
,
.
.
, .
, , .
,
, ,
, ,
,
.
OReilly Media,
Safari Books Online.
,
OReilly , http://
my.safaribooksonline.com.

b a ta


, ,
:
OReilly Media
1005 Gravenstein Highway N orth
Sebastopol, CA 95472
800-998-9938 ( )
707-829-0515 ()
707-829-0104 ()
,
:
http://www.oreilly.com/catalog/9780596802790

19


:
bookquestions@oreilly.com
, ,
OReilly :
http://www.oreilly.com

:
(Matt Sweeney), (Stoyan Stefanov),
(Steven Levithan), (Ross Harmes)
(Julien Lecomte).
, - .
,
, (Steve Souders), (Tenni Theurer)
(Nicole Sullivan). ,
-,
.
, ,
(Ryan Grove), (Oliver Hunt), (Matthew Russell), (Ted Roden),
(Remy Sharp) (Venkateswaran Udayasankar). ,
.
OReilly Yahoo!,
. Yahoo! ,
2006 , Yahoo! Press
.


JavaScript , ,
,
. JavaScript,
, JavaScript- .

JavaScript ,
-
. JavaScript-,
.
, <script>
, ,
. ,
, -

. ,
.
document.write()
( ).
:
<html>
<head>
<title>Script Example</title>
</head>
<body>
<P>
<script type="text/javascript">
document.write("The date is " + (new Date()).toDateString());
</script>
</p>

22

1.
</body>
</html>

<script>, HTML-, , JavaScript- -


<>,
.
,
. ,
src ;
, ,
.

.
JavaScript-
Yahoo! Exceptional Performance (http://developer.yahoo.com/perfor/) (Steve Souders), High Performance
Web Sites* (http://oreilly.com/catalog/9780596529307/) (OReilly)
Even Faster WebSites* (http://oreilly.com/catalog/9780596522315/)
(OReilly).
.


HTML 4 , <script> HTML-
<head> <body>
. <script>,
JavaScript-,
<head> <link>, CSS-,
. ,
,

. :
<html>
<head>
<title>Script Example</title>
<-- -->
<script type=text/javascript" src="file1.js"x/script>
<script type=text/javascript" src="file2. js"x/script>
<script type=,,text/javascript" src="file3. js"x/script>
clink rel=stylesheet" type="text/css" href="styles.css">
</head>
<body>
<p>Hello world!</p>
</body>
</html>

23

,
, : <head>
JavaScript-, .
<script>
,
. ,
,
<body>. ,
, ,
, -
-
. , ,
, ,
. . 1.1 ,
.

filel.js
Q ]

__

|
| ^

file2.js

1. . \

file3.js

styles.css

. 1.1. JavaScript-

. 1.1 .
JavaScript- .
filel.js
file2.js.
filel.js.
,
. ,
, .
.
Internet Explorer 8, Firefox 3.5, Safari 4 Chrome 2
JavaScript.
, <script> <script>
. , , JavaScript , .

, ,
JavaScript-,

24

1.

. ,

.
.
,
<script>
<body>, . :
<html>
<head>
<title>Script Example</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<p>Hello world!</p>
<-- -->
<script type="text/javascript" src="file1.js,,></script>
<script type="text/javascript" src="file2.js"x/script>
<script type=text/javascript" src="file3.js"x/script>
</body>
</html>

<script>
HTML-.
,
,
. , Yahoo!
Exceptional Performance, JavaScript-:
.


<script>
,
<script> . ,
. HTML <script>,
;
.
, (Steve Souders) ,
, <link>,
___I-4. ,
.

,
.
<link>.

25

JavaScript-. HTTP-
, 100
,
25 .
, .
- -
JavaScript-.
,
<script>.

( 9)
, ,
Yahoo!.
Yahoo!
Yahoo! User Interface (YUI)
(Content Delivery Network, CDN).
-
YUI, URL-
. , URL-
: http://yui.yahooapis.com/combo?2.7.0/build/yahoo/yahoomin.js&2.7.0/build/event/event-min.js.
URL- 2.7.0
yahoo-min.js event-min.js.

URL-. <script> (
) <script>,
:
<html>
<head>
<title>Script Example</title>
clink rel='stylesheet" type="text/css" href="styles.css>
</head>
<body>
<p>Hello world!</p>
<-- -->
<script type="text/javascript" src="
http://yui.yahooapis.com/combo?2.7.O/build/yahoo/yahoo-min.js&
2.7.0/build/event/event-min.js "></script>
</body>
</html>

,
<script>, JavaScript-,

JavaScript.

26

1.


JavaScript
( HTTP-, )
,
.
HTTP- -
-.
,
,
.
,
,
HTTP-. ,
, .
,
.
, ,
load window.
.


HTML 4
<script> defer. defer , ,
, DOM,
. defer
Internet Explorer 4+ Firefox 3.5+,
.
defer <script> (
) . ,
.
:
<script type="text/javascript" src="file1.js" deferx/script>

Ter <script> defer


. JavaScript-, ,
, <script>,
, DOM
( onload).
JavaScript-
,
.
<script>, defer,
, DOM .
, .

27

, defer
:
<html>
<head>
<title>Script Defer Example</title>
</head>
<body>
<script defer>
alertCdefer");
</script>
<script>
alert("script");
</script>
<script>
window.onload = function(){
alertC'load");

>;
</script>
</body>
</html>

.
, defer,
: defer, script load. ,
defer, : script, defer load.
, <script> defer
,
onload.
Internet Explorer Firefox 3.5,
.
, , .1

script
(Document Object Model, DOM)
JavaScript-
HTML-. <script>
:
DOM, ,
. <script>
DOM:
1 Internet Explorer 8 ( ) Firefox 3.6
HTML5 defer.
<script> defer
src. ,
.
Internet Explorer 8
.

28

1.
var script = document.createElement("script");
script.type = "text/javascript;
script.src = filel.js";
document.getElementsByTagName("head")[0].appendChild(script);

<script> filel.js.
, . ,

,
.
<head> , ,
(
HTTP-, ).

<script>
<head>, <body>,
. Internet Explorer
operation aborted ( ),
<body> .1


<script>,
( Firefox Opera,
,
<script>).
, ,

.
,
. ,
<script>.
Firefox, Opera, Chrome Safari 3+ load,
<script> src .
, ,
:
var script = document.createElement("script")
script.type = "text/javascript";
// Firefox, Opera, Chrome, Safari 3+
script.onload = function(){
alert("Script loaded!");

>;
script.src = "filel.js";
document.getElementsByTagName("head")[0].appendChild(script);

1 The dreaded
operation aborted error : http://www.nc2online.net/blog/2008/03/17/
the-dreaded-operationaborted-error/.

29

Internet Explorer ,
readystatechange. <script>
readyState,
. readyState
:
"uninitialized

.
"loading

.
"loaded"

.
"interactive"

, .
"complete"

.
Microsoft readyState
,

<script>, ,
.
"loaded" "complete". Internet Explorer
,
readyState -
<script> "loaded"
"complete", "complete",
"loaded".
readystatechange
( ,
):
var script = document.createElement("script")
script.type = "text/javascript";
// Internet Explorer
script.onreadystatechange = function(){
if (script.readyState == "loaded" || script.readyState == "complete"){
script.onreadystatechange = null;
alert("Script loaded.");

>
>;
script.src = "filel.js";
document.getElementsByTagName("head")[0].appendChild(script);


JavaScript-.
- IE:

30

1.
function loadScript(url, callback){
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState){ // IE
script.onreadystatechange = function(){
if (script.readyState=="loaded" || script.readyState=="complete"){
script.onreadystatechange = null;
callback();

>
>;
> else { //
script.onload = function(){
callback();

>;
>
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);

>
: URL- JavaScript-
, , JavaScript- .
,
<script>.
src
<script> .
loadScript():
loadScript("filel.js", function(){
alert("File is loaded!");

>);
JavaScript-, ,
. Firefox Opera ,
.
,
.
, , :
loadScript("file1.js", function(){
loadScript("file2.js", function(){
loadScript("file3.js", function(){
alert("All files are loaded!");

>);
>);
>);
file2.js,
filel.js, file3.js>

31

file2.js.
,
.
,
,
.
, (
,
).

,
.

XMLHttpRequest

XMLHttpRequest
(XHR) .
XMLHttpRequest, JavaScript-

<script>. :
var xhr = new XMLHttpRequest();
xhr.open(get", "filel.js", true);
xhr.onreadystatechange = function(){
if (xhr.readyState == 4){
if (xhr.status >= 200 && xhr.status < 30 0 || xhr.status == 304){
var script = document.createElement("script");
script.type = "text/javascript";
script.text = xhr.responseText;
document.body.appendChild(script);

>
>
>;
xhr.send(null);

GET- filel.js.
onreadystatechange , readyState
4, HTTP- (
200 299 , 304
, ).
<script>, text
responseText, .
<script> .
<script> ,
.

JavaScript- .

32

1.

<script>, ,
.
,
.
, JavaScript-
, , ,
CDN.
XHR
-.


JavaScript
:
, ,
, .

( loadScriptQ),

.

, JavaScript-. :
<script type="text/javascript" src="loader. js"x/script>
<script type="text/javascript">
loadScript("the-rest,js", function(){
Application.init();

>);
</script>


</body>. .
-, , ,

. -, JavaScript-
DOM ,
(
window.onload) ,
.
, loadScriptQ
HTTP-.
:
<script type="text/javascript">
function loadScript(url, callback){
var script = document.createElement("script")
script.type = "text/javascript";

33

if (script.readyState){ // IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();

>
>;
} else { //
script.onload = function(){
callback();

>;
>
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);

>
loadScript("the-rest.js", function(){
Application.init();

>);
</script>


, YUI Compressor
( 9), .
,
, loadScriptQ

.

YUI 3


YUI 3. YUI 3
, YUI:
<script type="text/javascript"
src="http://yui.yahooapis. com/combo?3.0.0/build/yui/yui-min. js"x/script>

10 (6
gzip)
YUI Yahoo! CDN. ,
DOM,
use() YUI ("dom") ,
,
:
YUI().use("dom", function(Y){
Y.DOM.addClass(document.body, "loaded");

>);

34

1.

YUI
use().
, "dorif
URL-,
, <script>,
.
,
YUI ,
.

LazyLoad
(Ryan Grove) Yahoo! Search
- LazyLoad ( http://github.com/rgrove/lazyload/). LazyLoad
loadScriptQ.
LazyLoad 1,5 (
, ).
:
<script type="text/javascript" src="lazyload-min. js"x/script>
<script type="text/javascript">
LazyLoad.js("the-rest.js", function(){
Application.init();

>);
</script>

LazyLoad JavaScript-
. JavaScript-,
LazyLoad.js() URL-:
<script type=,,text/javascript" src="lazyload-min.js"x/script>
<script type="text/javascript">
LazyLoad.js([first-file.js, "the-rest.js"], function(){
Application.init();

>);
</script>


,
, .
HTTP-,
,
.
LazyLoad
CSS-. ,
CSS-
.

35

LABjs

LABjs (http://labjs.com,/)> (Kyle Simpson)
(Steve Souders).

. , LABjs
- 4,5 ( ,
),
. :
<script type="text/javascript" src=lab.js"x/script>
<script type="text/javascript">
SLAB.script("the-rest.js")
.wait(function(){
Application.init();

});
</script>

$LAB.script() JavaScript-, $LAB.wait() - ,


.
LABjs
, $LAB.
JavaScript-,
$LAB.script():
<script type="text/javascript" src="lab.js"x/script>
<script type="text/javascript">
SLAB.script("first-file.js")
.script("the-rest.js")
.wait(function(){
Application.init();

>);
</script>

LABjs
.
<script> (
, ) .
, - .
LABjs wait
.
first-file.js therest.js. , wait
scriptQ:
<script type="text/javascript" src="lab.js></script>
<script type="text/javascript">
SLAB.script("first-file.js").wait()

36

1.
.script("the-rest. js")
.wait(function(){
Application.init ();

>);
</script>

first-file.js
the-rest.js>
.


JavaScript- -
,
, ,
. <script>,
,
( )
, .

JavaScript-:
<script>
</body>. ,
, .
. <script>
,
. ,
JavaScript-.
JavaScript-, :
defer <script> ( Internet Exp
lorer Firefox 3.5+).
<script>
.
JavaScript- XHR
.
,
-
JavaScript.

2


, .

. JavaScript
. ,
,
. Java
Script , :

,
- . JavaScript
, , ,
, , ,
null undefined.

,
var.

Array,
.

,
.

.

.

38

2.

,
.
. 2.1 200000
.
, Java
Script, Firefox 3, Internet Explorer Safari 3.2,
,
JavaScript.
:
,
. Firefox 3,

. ,
,

.
, .
100

90-

80-

0
|

60-

C\J

1 50-

Jo L40

'
1 30
i 20-

<>

Q.

10 -

0-

ill

. 2.1. 200000 ,



JavaScript ,
. JavaScript
,
, , this.

39

JavaScript
, ,
,
.



JavaScript ,
Function. ,
, ,
, , Ja
vaScript .
[[Scope]], -262,
(http://www.ecma-internationaLorglpublicationslstandardslEcma-262.htm).
[[Scope]] ,
, .

, .
,
/,
.
, ,
, . ,
:
function add(num1, num2){
var sum = num1 + num2;
return sum;

>
add()
: ,
.
, , , window, navigator document.
. 2.2
(
; ).

add)
[[Scope]]

^
this

window

window

()

document

()

add

()

. 2.2. add()

40

2.

add
. ,
:
var total = add(5, 10);

add ,
.
, .

,
.
, .
,
.

, [[Scope]]
.
.
,
.

, , arguments
this.
.
. . 2.3

.

var total = add(5,10);



0
1

------>

this

window

arguments

[5,10]

num1

num2

10

sum

undefined


this

window

window

()

document

()

add

()

total

undefined

. 2.3. add()

41


,
, ,
.
.
.
, ;
,
. ,

. ,
.
, ,

sum, num1 num2.
.
,

. ,
, ,
.


- ;
, ,
.
,
. ,
,
(
JavaScript
). ,

,
.
. 2.4 2.5
.
1 .
-
,

. JavaScript,
Chrome Safari 4,
,

42

2.

Internet Explorer, S afari 3.2


. ,
, Internet Explorer 6 Firefox 2,
,
,
.
IE7
>
s
S

160

140

IE8

1 120

Safari 3.2

I
|

80
60

Firefox 3
Firefox 3.5

00

40

20

Opera 10
Chrome
Safari 4

. 2.4.

. 2.5.

43


,
,
JavaScript.
,
. :
function initUI(){
var bd = document.body,
links = document.getElementsByTagName("a"),
i = 0,
len = links.length;
while(i < len){
update(links[i++]);

>
document.getElementById("go-btn").onclick = function(){
start();

>;
bd.className = "active";

>
document,
.
,
.

,

. , ,
:
function initUI(){
var doc = document,
bd = doc.body,
links = doc.getElementsByTagName("a"),

i = 0,
len = links.length;
while(i < len){
update(links[i++]);

>
doc.getElementByldCgo-btn^.onclick = function(){

start();

>;
bd.className = "active";

44

2.

initUIQ
document doc.
.
doc , document,
. ,
,
,

, -
.


,
. ,

. with.
with
. ,
, ,

. , initUIQ
:
function initUI(){
with (document){ // !
var bd = body,
links = getElementsByTagName("a"),

i = 0,
len = links.length;
while(i < len){
update(links[i++]);

>
getElementByldCgo-btn^.onclick = function(){

start();

>;
bd.className = "active";

>
}
initUIQ with,
document.
,
.
with,
.

45

,
. ,

, - (. 2.6).
with
body

()

getElementByld

()

getElementsByTagName

()


this

inHUIO

. J

window

arguments

[]

bd

undefined

links

undefined

undefined

len

undefined


this

window

window

()

document

()

add

()

total

undefined

. 2.6. with

document with
, document,
.
document,
, bd.
with. ,
document
.
with JavaScript,
;
catch try-catch. try
, catch,
-

46

2.

, . catch

. :
try {
methodThatMightCauseAnError();
} catch (){
alert(ex.message); //

>
, catch
.
try-catch ,

. , try-catch,
.
try-catch
JavaScript. , ,
,
.
catch
,
. ,
,
catch, :
try {
methodThatMightCauseAnError();
> catch (){
handleError(ex); //

>
handleErrorQ ,
catch.
, ,
.

,
.


with, catch try-catch,
, evalQ,
.

(
). :

47

function execute(code) {
eval(code);
function subroutine(){
return window;

>
var w = subroutine();
// w?

>;
executeQ ,
evalQ. w
code.
w window,
:
execute("var window = {};")

evalQ executeQ
window, w
, window.
, ,
, ,
window .
JavaScript,
Nitro Safari,
, , ,
.

,
.
.

, ,
.

, .

,
,
JavaScript,
.
(Douglas Crockford),
-.
.

48

2.

,
:
function assignEvents(){
var id = xdi9592;
document.getElementById("save-btn").onclick = function(event){
saveDocument(id);

>
assignEventsQ
DOM. ,
assignEventsQ,
id,
. id ,
.
assignEventsQ ,
id.
;
. ,
[[Scope]] (. 2.7).


this

[[Scope])

3/

assignEventsQ

_>

------

0
1

window

arguments

[]

id

"xdi9592"


* this

window

window

()

document

()

assignEvents

()

saveDocument

()

. 2.7.
assignEventsf)
[[Scope]]
, ,
. -

49


.
,
[[Scope]] . ,
, , . -
,
Internet Explorer. IE DOM
JavaScript-,
( 3).
, ,

,
[[Scope]],
(. 2.8).
() '

[[Scope]]

this

window

arguments

[]

event

()

(assignEvents) i
this

window

------

arguments

[]

------

id

"xdi9592"

1
2


this

window

window

()

document

()

assignEvents

()

saveDocument

()

. 2.8.

, , id saveDocument,
,
.
:
,

50

2.


.
,

.
, ,
, :

.


JavaScript - , ,
,
DOM BOM (Browser Object Model -
).
.
, , J a
vaScript .
. Java
Script ,
. ,
, , ,
, - .
,
,
, ,
. , ,
JavaScript.

JavaScript . -
, ,
, .

- ,
. -
,
-.
.
Firefox, Safari Chrome
_proto__;
. , ,

51

Object, Date Array,


Object - .
, :
( ) .
,
-.
:
var book = {
title: "High Performance JavaScript",
publisher: "Yahoo! Press"

};
alert(book.toStringO); // "[object Object]"

book : title publisher.


, toSt ing (),
, , .
toStringO - , book.
. 2.9.
book
_proto_

_proto_

title

"High Performance
JavaScript*

hasOwnProperty

()

isPrototypeOf

()

propertylsEnumerable

()

publisher

"Yahoo! Press"

null

toLocaleString

()

toString

()

valueOf

()

. 2.9.


. book.toStringO,
toString
. book toString,
-,
toStringO. , book
.

hasOwnPropertyO, .
,
, in. :

52

2.
var book = {
title: "High Performance JavaScript",
publisher: "Yahoo! Press"

};
alert(book.hasOwnPropertyC'title"));
// true
alert(book.hasOwnPropertyCtoString")); // false
alert("title" in book);
// true
alert("toString" in book); // true

, hasOwnPropertyQ title,
true, title ;
toString, false,
.
in,
true, ,
.



. Object
, toStringQ.
,
. :
function Book(title, publisher){
this.title = title;
this.publisher = publisher;

>
Book.prototype.sayTitle = function(){
alert(this.title);

};
var bookl = new Book("High Performance JavaScript", "Yahoo! Press");
var book2 = new Book("JavaScript: The Good Parts", "Yahoo! Press");
alert(book1 instanceof Book);
// true
alert(book1 instanceof Object); // true
bookl.sayTitle();
// "High Performance JavaScript"
alert(book1.toStringO); // "[object Object]"

Book
Book. (_proto__) bookl Book.proto
type, Book.prototype - Object.
,
bookl 2 .
. 2.10.

53

_proto_

Book prototype

title

"High Performance
JavaScript"

publisher

"Yahoo! Press"

_proto_

Book.prototype
_proto_

hasOwnProperty

()

isPrototypeOf

()

sayTitle
_proto_

()

Book

title

"JavaScript:
TheGood Parts"

publisher

"Yahoo! Press"

null

propertylsEnumerable ()
toLocaleString

()

toString

()

valueOf

()

. 2.10.

, Book
.
t i tle publisher, .
, book1.toString(),
, toString
. ,
,
. . 2.11
.
350-|

1 300
15
250


2-

3-

200

S
31" 150

1 100

50

&

. 2.11.

54

2.

,
JavaScript, ,
- Internet Explorer Firefox 3.5 -

. ,
,
,
.


, JavaScript- , ,
: window.location.href.
JavaScript
. . 2.12
.
,
, . location.href
, window, location, href,
, , ,
window.location.href.toStringQ. , ,
, -
.
250

200 -

150

100

50-

Firefox 3.5
Chrome
Safari 4

. 2.12.

55



(object, name)
(object["name"]). Safari - ,
,
,
.



, ,
, . ,
, .
,
:
function hasEitherClass(element, classNamel, className2){
return element.className == classNamel || element.className == className2;

>
element.class
Name. ,
,
.
,
:
function hasEitherClass(element, classNamel, className2){
var currentClassName = element.className;
return currentClassName == classNamel || currentClassName == className2;

>

. -
,
.
.
,
,
.
,
.
,
.
, , , YUI,
. :

56

2.
function toggle(element){
if (YAHOO.util.Dom.hasClass(element, "selected")){
YAHOO.util.Dom.removeClass(element, "selected");
return false;
} else {
YAHOO.util.Dom.addClass(element, "selected");
return true;

}
}
YAHOO.util.Dom
.
.
, .
,
YAHOO, u til. Dom :
function toggle(element){
var Dom = YAHOO.util.Dom;
if (Dom.hasClass(element, "selected")){
Dom.removeClass(element, "selected");
return false;
} else {
Dom.addClass(element, "selected");
return true;

}
}

.
, .
:
.
this ,
this
window. this
, JavaScript
,
.

57


, JavaScript-,

. ,
: , ,
. .

,
.
,
,
.
,
.
,
.
with,
.
catch
try-catch, .

,
.
,
.
, JavaScript-
, ,
.
, .
,
-,
.

3
DOM

(Stoyan Stefanov)

DOM

-.
DOM,
,
. :
DOM
DOM,

DOM
DOM ,
.

DOM
(Document Object Model, DOM) -
(API) XML HTML-. HTML, - XML- DOM API , .
API,
,
JavaScript.
, --

D O M

59

, DOM
JavaScript.
DOM
JavaScript. Internet Explorer, , Java
Script JS cript
jscript.dll, DOM
, mshtml.dll ( Trident).
, VBScript,
DOM
Trident. Safari DOM
WebCore ,
WebKit, JavaScriptCore ( SquirrelFish).
Google Chrome
WebCore WebKit,
JavaScript V8. Firefox
JavaScript SpiderMonkey (
TraceMonkey),
Gecko.


?
, ,
.
, DOM JavaScript ( Script) , (
(John H rvatin), Microsoft, MIX09, http://videos.visitmix.com/
MIX09/T53F). , ECMAScript
DOM,
.
DOM, .

ECMAScript.
,
,
.

DOM
DOM , .
,
.
,
, HTML.

60

3. D O M

,
DOM, :
function innerHTMLLoop() {
for (var count = 0; count < 15000; count++) {
document.getElementById('here').innerHTML += 'a';

}
>
.
,
:
innerHTML, .
,

:
function innerHTMLLoop2() {
var content = '';
for (var count = 0; count < 15000; count++) {
content += a';

>
document. getElementById(here).innerHTML += content;

}

. . 3.1
. Y (

273

263

250-

155
150112

122
101

98

100 -

43

50-

' --- I IT 1 --, rJ--


/ / $>

43

I ~~ I

34

20

- JZ
L 1
* $>

. 3.1. ,
ECMAScript: innerHTMLLoop2()
innerHTMLLoopf)

61

D O M

) ,
.
innerHTMLLoop2() IE6 155
innerHTMLLoopQ.

,
DOM
. , :
DOM ECMAScript
.

innerHTML DOM
-
: ,
, innerHTML,
DOM, document.createElementQ?
- ,
-? , , ,
innerHTML ,
, WebKit (Chrome Safari).
1000 :
HTML
innerHTML DOM.
DOM,
document.createElementQ document.createTextNodeQ.
,
(Content Manage
ment System, CMS). . 3.2.
id

yes?

name

And the answer is... yes

my name is #1

And the answer is... no

my name is #2

u rl

action
edit
delete

http://cxample.orp/2 .html

1
delete

II.......I................................. I.........................-I ........................................


. 3.2. HTML- 1000
5


innerHTML:
function tablelnnerHTMLO {
var i, h = [<table border="1" width="100%">'];

62

3.
h.push(<thead>);
h.push('<trxth>id<\/thxth>yes?<\/thxth>name<\/thxth>url<\/th>' +
<th>action<\/thx\/t r> );
h.push('<\/thead>');
h.push(<tbody>);
for (i = 1; i <= 1000; i++) {
h. push( <trxtd>);
h.push(i);
h.push( ,<\/tdxtd>);
h.push('And the answer is... ' + (i % 2 ? 'yes' : no));
h. push( '<\/tdxtd>');
h.push('my name is #' + i);
h. push( '<\/tdxtd>');
h.push('<a href="http://example.org/' + i +
'.html">http://example.org/' + i + '.html<\/a>);
h. push( '<\/tdxtd>');
h.push('<ul>);
h.pushC <li><a href="edit. php?id= + i + ,,>edit<\/ax\/li>');
h.pushC <li><a href="delete.php?id=" + i + '">delete<\/ax\/li>');
h.push('<\/ul>');
h.push('<\/td>');
h.push('<\/tr>');

h.push(<\/tbody>');
h.push(<\/table>');
document. getElementById(here'). innerHTML = h.join( );

};
, DOM,
:
function tableD0M() {
var i, table, thead, tbody, tr, th, td, a, ul, li;
tbody = document.createElement('tbody');
for (i = 1; i <= 1000; i++) {
tr = document.createElement('tr');
td = document.createElement('td');
td.appendChild(document.createTextNode((i % 2) ? 'yes'
no'));
tr.appendChild(td);
td = document.createElement(td');
td.appendChild(document.createTextNode(i));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode('my name is #' + i));
tr.appendChild(td);

D O M
= document.createElement('');
a.setAttributeChref', 'http://example.org/' + i + .html);
a.appendChild(document.createTextNode('http://example.org/' + i +
'.html'));
td = document.createElement(td);
td.appendChild(a);
tr.appendChild(td);
ul = document.createElement('ul');
a = document.createElement('a');
a.setAttributeChref', 'edit.php?id=' + i);
a.appendChild(document.createTextNode('edit'));
li = document.createElement('li');
li.appendChild(a);
ul.appendChild(li);
a = document.createElement('a');
a.setAttributeChref', 'delete.php?id=' + i);
a. appendChild(document.createTextNode('delete'));
li = document.createElement li');
li.appendChild(a);
ul.appendChild(li);
td = document.createElement('td');
td.appendChild(ul);
tr.appendChild(td);
tbody.appendChild(tr);

}
tr = document.createElement('tr');
th = document.createElement('th');
th.appendChild(document.createTextNode('yes?'));
tr.appendChild(th);
th = document.createElement('th');
th.appendChild(document.createTextNode('id'));
tr.appendChild(th);
th = document.createElement('th');
th.appendChild(document.createTextNode('name'));
tr.appendChild(th);
th = document.createElement('th');
th.appendChild(document.createTextNode('url'));
tr.appendChild(th);
th = document.createElement('th');
th.appendChild(document.createTextNode('action'));
tr.appendChild(th);
thead = document.createElement('thead');
thead.appendChild(tr);
table = document.createElement('table');
table.setAttribute('border', 1);
table.setAttribute('width', *100%');
table.appendChild(thead);

63

64

3. D O M
table.appendChild(tbody);

document.getElementById('here).appendChild(table);

};
HTML-
innerHTML DOM
. 3.3. innerHTML
( IE6 innerHTML
3,6 ) .
, WebKit,
: DOM
. ,
, ,
.
innerHTML
,
HTML-.
,
,
, ,
.

. 3.3. innerHTML DOM


1000 ; IE6 innerHTML
, WebKit

D O M

65



DOM DOM . , -
element.cloneNodeQ ( element )
document.createElementQ.
,
.


:
2% IE8, IE6 IE7
5,5% Firefox 3.5 Safari 4
6% Opera ( Opera 10)
10% Chrome 2 3% Chrome 3
,
element.cloneNodeQ:
function tableClonedDOM() {
var i, table, thead, tbody, tr, th, td, a, ul, li,
oth = document.createElement('th'),
otd = document.createElement('td'),
otr = document.createElement('tr'),
oa = document.createElement('a'),
oli = document.createElement('li'),
oul = document.createElement(ul');
tbody = document.createElement(tbody');
for (i = 1; i <= 1000; i++) {
tr = otr.cloneNode(false);
td = otd.cloneNode(false);
td.appendChild(document.createTextNode((i % 2) ? 'yes' : 'no'));
tr.appendChild(td);
td = otd.cloneNode(false);
td.appendChild(document.createTextNode(i));
tr.appendChild(td);
td = otd.cloneNode(false);
td.appendChild(document.createTextNode(my name is #' + i));
tr.appendChild(td);
// ... ...

}
// ... ...

66

3. D O M

HTML-
HTML- - , ,
DOM. ,
:

document.getElementsByNameQ

document. getElementsByClassNameQ

document.getElementsByTagName()

HTML-:
document.images

<img> .
document.links

<> <> <href>.


document.forms

.
document. forms[0]. elements

.
HTMLCollection,
.
( , push() sliceQ),
length
. , document.images[1]
. DOM,
HTML- ,
(http://
www.w3.org/TR/DOM-Level-2-HTML/htmLhtml#ID-75708506).
HTML- ,
,
,
( length ).
.


, ,
:
//
var alldivs = document.getElementsByTagName(div);
for (var i = 0; i < alldivs.length; i++) {
document.body.appendChild(document.createElement('div'))

}

<div> .

67

D O M

<div> <div>,
. ,
, alldivs.length,
, ,
.
HTML-
,
- ,
(. 3.4).
200 - |

191

150114
10079
58x
50 14,2x 14,9x
2x

' ^
&

3,5x

5,7

3,5

. 3.4. ,
HTML-

4,
length .
length ,
length ,
.
, coll,
.
, HTML-
:
function toArray(coll) {
for (var i = 0, a = [], len
a[i] = coll[i];

}
return a;

coll.length; i < len; i++) {

68

3.

:
var coll = document.getElementsByTagName('div');
var ar = toArray(coll);

:
//
function loopCollection() {
for (var count = 0; count < coll.length; count++) {
/ * * /

}
}
//
function loopCopiedArrayO {
for (var count = 0; count < arr.length; count++) {
/ * * /

)
)
length
,
.
,

:
function loopCacheLengthCollection() {
var coll = document.getElementsByTagName(div'),
len = coll.length;
for (var count = 0; count < len; count++) {
/ * */

}
}
, loopCopiedArrayO.
,
,
length .
,
,
, .
,
,
,

.
toArrayO, ,

.

D O M

69



,
,
?
:
DOM ,
DOM .

- length
,
.

.
document,
,

. length
.
//
function collectionGlobal() {
var coll = document, getElementsByTagNaine( 'div'),
len = coll.length,
name = '';
for (var count = 0; count < len; count++) {
name = document.getElementsByTagName('div')[count].nodeName;
name = document.getElementsByTagName('div')[count].nodeType;
name = document.getElementsByTagName('div')[count]. tagName;

}
return name;

};
//
function collectionLocalO {
var coll = document.getElementsByTagName('div'),
len = coll.length,
name = '';
for (var count = 0; count < len; count++) {
name = coll[count].nodeName;
name = coll[count].nodeType;
name = coll[count].tagName;

}
return name;

70

3.
//
function collectionNodesLocal() {
var coll = document.getElementsByTagName(div),
len = coll.length,
name = '',
el = null;
for (var count = 0; count < len; count++) {
el = coll[count];
name = el.nodeName;
name = el.nodeType;
name = el.tagName;

}
return name;

};
. 3.5
.
,
, -
,
.

350 -I
300250200
150100 50-

X XX
X
><! w
0 5 <.

csT csT
LO CVI

X- (X,><
*
- 1^.10 ^
\ \ ^ ^
&

&

. 3.5.

D O M

71

DOM
DOM
. ,
,
API.

DOM

DOM , ,
.
, childNodes
nextSibling.

:
function testNextSibling() {
var el = document.getElementById('mydiv*),
ch = el.firstChild,
name = **;
do {
name = ch.nodeName;
} while (ch = ch.nextSibling);
return name;

};
function testChildNodes() {
var el = document.getElementById(mydiv),
ch = el.childNodes,
len = ch.length,
name = ;
for (var count = 0; count < len; count++) {
name = ch[count].nodeName;

}
return name;

};
, childNodes - ,
.
length,
.

. IE nextSibling
, childNodes. IE6 nextSibling 16
, IE7 - 105 . , ,
, DOM
IE next
Sibling.
.

72

3.

-
DOM, childNodes, firstChild nextSibling, ,
(
).
, ,
,
.
DOM.
,
, .
, ,
, ,
. DOM . 3.1.
3.1. DOM,
(HTM L-)

children

childNodes

childElementCount

childNodes.length

firstElementChild

firstChild

lastElementChild

lastChild

nextElementSibling

nextSibling

previousElementSibling

previousSibling

, . 3.1,
Firefox 3.5, S afari 4, Chrome 2 Opera 9.62. 6 7 Inter
net Explorer children.
children ,
childNodes, .
, HTML
, children. children
, childNodes,
1,5 3 .
IE, children
, childNodes, - 24
IE6 124 IE7.

API

DOM, getElementByldQ getElementsByTagNameQ. ,

D O M

73

,
.

CSS- - CSS. JavaScript- ,
CSS-,
DOM- querySelectorAllQ.
, , JavaScript
DOM .
:
var elements = document.querySelectorAll(#menu a');

elements
<>, id=menu". querySelectorAllQ CSS-
NodeList - , , ,
. , ,
HTML-,
.
(
), HTML-
.
querySelectorAllQ, :
var elements = document.getElementById(menu).getElementsByTagName();

elements HTML-,
,
, querySelectorAllQ.

querySelectorAll() ,
. ,
<div> warning, notice,
querySelectorAll() :
var errs = document.querySelectorAll('div.warning, div.notice');

querySelectorAllQ, .
, <div>
, .
var errs = [],
divs = document.getElementsByTagName('div'),
classname = ;
for (var i = 0, len = divs.length; i < len; i++) {
classname = divs[i].className;

74

3. D O M
if (classname === 'notice' || classname === 'warning') {
errs.push(divs[i]);

}
}
,
querySelectorAll() 2 -6 (. 3.6).

81
7.

6-

4,88

5
.

4
0m

1X -

Q-

2,46
2

2 -

!*

3,45

Jb

2,1

</

. 3.6. API
, getElementsbyTagNamef)
API , : Internet
Explorer 8, Firefox 3.5, S afari 3.1, Chrome 1 Opera 10.
, . 3.6,
document.querySelectorAllQ
, . ,
API , JavaScript-,
,
API. , ,
.
querySelector(), , .
DOM,
document.querySelector('.myclass ),
elref. querySelector(myclass), elref - DOM.

75


- HTML,
JavaScript, CSS, -

:
DOM
.

DOM.
, ,
DOM, (
DOM
). ,
, CSS,
, , ,
. ,
() .
DOM ,
( ),
,
,
, .
, ,
. (reflow).

, (repaint).
DOM
. ,
.
( ), .


-.
, , .

?
, ,
. , :
DOM

(, -
, , , . .)

76

3. DOM

, ,




.
,
.



- ,
,
,
. ( )
.
,
,
:

offsetTop, offsetLeft, offsetWidth, offsetHeight

scrollTop, scrollLeft, scrollWidth, scrollHeight

clientTop, clientLeft, clientWidth, clientHeight

getComputedStyleQ (currentStyle IE)


,
,
.

, .

,
.
,
(
,
):
//
var computed,
tmp = '',
bodystyle = document.body.style;
if (document.body.currentStyle) { // IE, Opera
computed = document.body.currentStyle;

77


} else { // W3C
computed = document.defaultView.getComputedStyle(document.body,

>
//
//
bodystyle.color = *red';
tmp = computed.backgroundColor;
bodystyle.color = 'white';
tmp = computed.backgroundlmage;
bodystyle.color = 'green';
tmp = computed.backgroundAttachment;


<body>,
. - backgroundColor, backgro
undlmage backgroundAttachment -
.
, ,
.
,
,
.
,
:

6
5,27
5-

3-

2,72
2,3

1,83 1,87

2,55 2,54

1,94

1,04 1,2 1,05

. 3.7,

78

3. D O M
bodystyle.color = red;
bodystyle.color = 'white';
bodystyle.color = 'green';
tmp = computed.backgroundColor;
tmp = computed.backgroundlmage;
tmp = computed.backgroundAttachment;

,
. 3.7.




,
, .

DOM .


:
var el = document.getElementByld( 'mydiv');
el.style.borderLeft = '1px';
el.style.borderRight = '2px';
el.style.padding = '5px';

,
.
.

,

(,
). -
, ,
. ,
DOM ,
.


DOM .
cssText:
var el = document.getElementById('mydiv');
el.style.cssText = 'border-left: 1px; border-right: 2px; padding: 5px;';

cssText, ,
,

79

,
cssText:
el.style.cssText +=

border-left: 1px;;


CSS- .
,
. CSS-
;
, ,

- .
var el = document.getElementByld(mydiv);
el.className = 'active';

DOM
DOM
,
:
1. .
2. .
3. .
-
1 3. ,
2 .

DOM :
, .
,
DOM .
,
.

,
:
<ul id="mylist>
<li><a href=http://phpied.com">Stoyan</a></li>
<li><a href="http://]ulienlecomte.com>Julien</a></li>
</ul>

, ,
, :
var data = [

80

3.
"name": "Nicholas",
"url": "http://nczonline.net"

},
{
"name": "Ross",
"url": "http://techfoolery.com"

}
];
,
:
function appendDataToElement(appendToElement, data) {
var a, li;
for (var i = 0, max = data.length; i < max; i++) {
a = document.createElement(a');
a.href = data[i].url;
a.appendChild(document.reateTextNode(data[i].name));
li = document.createElement(li');
li.appendChild(a);
appendToElement.appendChild(li);

}
};
,
, :
var ul = document.getElementByld(mylist);
appendDataToElement(ul, data);

data
DOM
. ,
,
<ul> ,
display, :
var ul = document.getElementById(mylist');
ul.style.display = none;
appendDataToElement(ul, data);
ul.style.display = block';

-

.
- document,
- .

,
, .
,
DOM :

81

var fragment = document.createDocumentFragment();


appendDataToElement(fragment, data);
document.getElementById(mylist').appendChild(fragment);

, ,

:
var old = document.getElementById('mylist');
var clone = old.cloneNode(true);
appendDataToElement(clone, data);
old.parentNode.replaceChild(clone, old);

(
), ,
DOM
.
,
, -
.


,

.
, ,
,
, , .

,
.
myElement
100x100 500x500 .

:
//
myElement.style.left = 1 + myElement.offset Left + *px;
myElement.style.top = 1 + myElement.offsetTop + 'px';
if (myElement.offsetLeft >= 500) {
stopAnimation();

>
,
,

.
,
,

82

3. D O M

var current = myElement.offsetLeft;.



current, :
current++
myElement.style.left = current + px;
myElement.style.top = current + 'px';
if (current >= 500) {
stopAnimation();

>



/

.
,
.

,
.
, .
,
, ,
.
, .

:
1. ,
, ,
.
2. . ,
.

.
3.
,
, .

IE :hover
7 IE CSS :hove
( ).

. IE8.

83

, 500-1000 5
tr:hover
, ,
, .
, CPU 80-90% .

,
.


,
(
onclick), .

- (
JavaScript),
.
DOM ,
,
onload ( DOMContentReady) -
-,
.
, , ,
,
. ,
( ,
, ,
100 ),
.
DOM
. ,
,
.

, ,
.
DOM
:



IE,
.
, . 3.8.

84

3. D O M

v c h tm l

x m ln s " h ttp //w w N v.w 3.org/1 9 9 9 /x h tm l * x m l:ta n g " c n ' lan g -^ cn *


< head>
< body>

<d:V>

<u! id-'menu*

<li>

<a href" menul.htnrr> menu #l</a>


</h>
< II>

<li>
<li>
< /u l>

______ </>_________________________________________

. 3.8. DOM
menu #1, click
<>. D O M
<li>, <ul>, <div> . .
window.

,
.
, , . 3.8,
Ajax.
JavaScript,

. JavaScript
,
,
( ), Ajax-

.
,
click <ul> id-'menu",
click,
.
document.getElementById(menu).onclick = function(e) {
//
= || window.event;
var target = e.target || e.srcElement;
var pageid, hrefparts;
//
// , click
if (target.nodeName !== ) {
return;

>

85


//
hrefparts = target.href.split('/);
pageid = hrefparts[hrefparts.length - 1];
pageid = pageid.replace(.html', *');
//
ajaxRequest(xhr.php?page=' + pageid, updatePageContents);
//
//
if (typeof .preventDefault === 'function') {
.preventDefault();
e.stopPropagation();
} else {
e.returnValue = false;
e.cancelBubble = true;

>
>;
,
; ,
, .
, ,
, .
, ,
:

( );
(
);
(,
, ,
).


DOM
-.
, ECMAScript DOM,
. ,
DOM, :
DOM
JavaScript.

DOM, .
HTML-,
. -

86

3. DOM

length
, ,
.
API, , querySelectorAllQ firstElementChild.
;
, DOM
,
.

.

.

4



, .
, ,

.
.
, ,
JavaScript
.
, ,
, JavaScript ,
,
,
.


.

, ,
,
. , JavaScript
, ,

.

88

4.


-262,
JavaScript, .
- for, ,
- :
for (var i=0; i < 10; i++){
//

>
for JavaScript
. for :
, ,
. for,
, .
true, .
.
for .
, var
for , ,
. JavaScript
,
for
.

- while. while -
,
:
var i = 0;
while(i < 10){
//
i++;

>

. true,
; . for
while, .
- do-while. do-while
JavaScript,
, -
:
var i = 0;
do {
//
} while (i++ < 10);

89

do-while ,

.
- for-in.
:
. :
for (var prop in object){
//

>
prop (
) . ,
.
, .



.
, JavaScript, for-in
.
for-in
,

. for-in
, .
for-in,

. , ,
,
, :
var props = [propl, "prop2"],
i = 0;
while (i < props.length){
process(object[props[i++]]);

>
,
. while
.

, , .
for-in .

90

4.

for-in,
,
.
, .
, ?
:
,


.

,

, ,
.
, ,
.

.
:
//
for (var i=0; i < items.length; i++){
process(items[i]);

>
var j=0;
while (j < items.length){
process(items[j++]);

>
var k=0;
do {
process(items[k++]);
} while (k < items.length);


:
1. (items, length) .
2. ^ < items, length) .
3. (i < items,
length == true).

4. (i++).
5. (items[i]).
6. (process(items[i])).

91


, .
,
processQ ,
,
, .
, ,

. 2,
,
.

items, length. .
,
.
,

, :
//
for (var 1=0, len=items.length; i < len; i++){

process(items[i]);

}
var j=0,
count = items.length;
while (j < count){

process(items[j++]);

}
var k=0,
num = items.length;

do {
process(items[k++]);
} while (k < num);


length .


.
25%
( 50% Internet Explorer).
,
.
,
.

92

4.

, . JavaScript

:
//

for (var i=items.length; i ; ){


process(items[i]);

}
var j = items.length;
while (j ){
process(items[j]);

}
var k = items.length-1;
do {
process(items[k]);

} while (k);



.
.
true, ,
, true,
false. ,
(
true),
(
true).
.


50-60% .
,
:
1. (i == true) .
2. ^--).
3. (items[i]).
4. (process(items[i])).

, ,
.
m '

, ,
, ().
, (),
.

93



, . ,
,
, .
,
.

(D uffs Device)1.
- ,

. ,
JavaScript (Jeff Greenberg).
, :
// : (Jeff Greenberg)
var iterations = Math.floor(items.length / 8),
startAt = items.length % 8,
i
= 0;
do {
switch(startAt){
case 0: process(items[i++]);
case 7: process(items[i++]);
case 6: process(items[i++]);
case 5: process(items[i++]);
case 4: process(items[i++]);
case 3: process(items[i++]);
case 2: process(items[i++]);
case 1: process(items[i++]);

}
startAt = 0;
} while (iterations--);

,

process().
.
, startAt,
processQ
. , 12 ,
processQ 4 ,
- 8 , 12.

switch
:
1

http://ru.wikipedia.org/wiki/ycmpoiLcmeo _ - . .

94

4.
// : (Jeff Greenberg)
var iterations = items.length % 8;
i
= items.length - 1;
while(iterations){
process(items[i--]);
iterations--;

}
iterations = Math.floor(items.length / 8);
while(iterations){
process(items[i--]);
process(items[i--]);
process(items[i--]);
process(items[i--]);
process(items[i--]);
process(items[i--]);
process(items[i--]);
process(items[i--]);
iterations--;

}
,
switch
.


.
1000 ,
.
1000
.
, , 500000 ,
70%.


-262
, forEachQ.

. ,
forEachQ ,
: , .
:
items.forEach(function(value, index, array){
process(value);

});
forEachQ Firefox, Chrome Safari. ,
JavaScript- :

95

// YUI 3
Y.Array.each(items, function(value, index, array){
process(value);

});
// jQuery
jQuery.each(items, function(index, value){
process(value);

});
// Dojo
dojo.forEach(items, function(value, index, array){
process(value);

});
// Prototype
items.each(function(value, index){
process(value);

});
// MooTools
$each(items, function(value, index){
process(value);

});

,
.
,
.

,
.


, ,
. if-else
switch JavaScript ,
.
-
, .

if-else switch
, if-else switch
:
, if-else
switch. -

96

4.

. if-else
, switch -
. :
if (found){
//
} else {
//

}
switch(found){
case true:
//
break;
default:
//

}
, ,
if-else , switch.

:
if (color == "red"){
//
} else if (color == ,,blue,,){
//
} else if (color == "brown"){
//
} else if (color == "black"){
//
} else {
//

}
switch (color){
case "red":
//
break;
case "blue":
//
break;
case "brown":
//
break;
case "black":
//
break;
default:
//

}
switch .

97

, switch
, if-else,
.


if-else. ,
if-else
switch -
.
, if-else ,
,
.
, switch.

if-else
if-else
,
.
,
. :
if (value < 5) {
//
} else if (value
//
} else {
//

> 5 && value < 10) {

}
,
value 5.
10,
,
.
, if-else
.

if-else
if-else. if-else
-
. :
if (value == 0){
return resultO;
} else if (value == 1){
return resultl;
} else if (value == 2){
return result2;

98

4.
} else if (value == 3){
return result3;
} else if (value == 4){
return result4;
} else if (value == 5){
return result5;
} else if (value == 6){
return result6;
} else if (value == 7){
return result7;
} else if (value == 8){
return result8;
} else if (value == 9){
return result9;
} else {
return resultIO;

}
if-else 10 .
, value
0 10.
,
if-else, :
if (value < 6){
if (value < 3){
if (value == 0){
return resultO;
} else if (value == 1){
return resultl;
} else {
return result2;

}
} else {
if (value == 3){
return result3;
} else if (value == 4){
return result4;
} else {
return result5;

}
}
} else {
if (value < 8){
if (value == 6){
return result6;
} else {
return result7;

99

} else {
if (value == 8){
return result8;
} else if (value == 9){
return result9;
} else {
return resultIO;

}
}
}
if-else
value.
,

.
value
0 10
if-else.
,
(
,
switch).


,
if-else switch, ,
.
, if-else switch,
, ,
.
,
, if-else
switch, (. 4.1).
if-else switch,
,
.
, switch ,
:
switch(value){
case 0:
return resultO;
case 1:
return resultl;
case 2:
return result2;
case 3:

100

4.
return
case 4:
return
case 5:
return
case 6:
return
case 7:
return
case 8:
return
case 9:
return
default:
return

result3;
result4;
result5;
result6;
result7;
result8;
result9;
resultIO;

}
, switch
, .
, :
//
var results = [resultO, result1, result2, result3, result4, result5, result6,
result7, result8, result9, resultIO]
//
return results[value];

---- 1------- 1------- 1------- 1------- 1------- 1------- 1------- 1------- 1------- 1------- 1

10

11

. 4.1.
if-else switch Internet Explorer 7

101


.
.
:

, ,
.
,
(
). switch ,

.

.
,
. ,
:
function facto rial(n){
if (n == 0){
return 1;
} else {
return n * factorial(n-1);

>
>

,
, .
,
.


JavaScript
. Internet
Explorer,
,
.

( Safari 2, , 100 ).
. 4.2 .

,
:

102

4.

Internet Explorer: Stack overflow at line (


)
Firefox: Too much recursion ( )
Safari: Maximum call stack size exceeded (
)
Opera: Abort (control stack overflow) ( (-
))
Chrome - , ,
.
40000 -1

37448

35000 30000

2
a

25000 -

21837 21837

20000
.
150002

100005000 -

10000 10000
3000 3000

1789

2232

500

0-

< < /

< /

. 4.2.
, , ,
, ,
JavaScript,
t ry-catch. . Firefox InternalError, Safari Chrome - RangeError, Internet Explorer
Error. (Opera
, Java
Script.)
JavaScript-:
try {
recurse();
} catch (){
alert("Too much recursion!");

>

103

, ,
( Firefox Firebug
; Safari/Chrome
JavaScript). Internet Explorer - IE
JavaScript,
, alertQ,
.
*

JavaScript-, . ,
,
.



,
.
. - ,
factorial) ,
. :
function recurse(){
recurse();

>
recurse();


. , ,
:
function first(){
secondO;

>
function second(){
first();

>
first();

, ,
.
.

.
,

104

4.

.
, ,
, ,
,
, .


.
, ,

.

,

.
,
.
JavaScript :
function merge(left, right){
var result = [];
while (left.length > 0 && right.length > 0){
if (left[0] < right[0]){
result.push(left.shift());
} else {
result.push(right.shift());

>
>
return result.concat(left).concat(right);

>
function mergeSort(items){
if (items.length == 1) {
return items;

>
var middle = Math.floor(items.length / 2),
left = items.slice(0, middle),
right = items.slice(middle);
return merge(mergeSort(left), mergeSort(right));

}
,
, m e r g e S o r t Q

105

.
.

; ,

.
, :
// merge()
function mergeSort(items){
if (items.length == 1) {
return items;

>
var work = [];
for (var i=0, len=items.length; i < len; i++){
work.push([items[i]]);

>
work.push([]); //
for (var lim=len; lim > 1; lim = Math.floor((lim+1)/2)){
for (var j=0,k=0; k < lim; j++, k+=2){
work[j] = merge(work[k], work[k+1]);

>
work[j] = [];//

>
return work[0];

>
mergeSort() ,
, .

,
. -
.

-
. ,
. ,
,
,
. - ,

,
.

106

4.


, .

f a c to r ia l),
. :
var fact6 = factorial(6);
var fact5 = factorial(5);
var fact4 = factorial(4);

,
factorial() 18 .
,
. 6 -
6 5, 5
. , 4 .

,
.
, factorial() ,
:
function memfactorial(n){
if (!memfactorial.cache){
memfactorial.cache = {
"": 1,
"I":

>;
>
if (!memfactorial.cache.hasOwnProperty(n)){
memfactorial.cache[n] = n * memfactorial(n-1);

>
return memfactorial.cache[n];

>
f actorial()
cache,
.
0 1.
cache
.

.
,
factorialQ:

107

var fact6 = memfactorial(6);


var fact5 = memfactorial(5);
var fact4 = memfactorial(4);

,
memfactorialQ.
,

, .

,
. ,
memoize(), .
:
function memoize(fundamental, cache){
cache = cache 11 {};
var shell = function(arg){
if (!cache.hasOwnProperty(arg)){
cache[arg] = fundamental(arg);

>
return cache[arg];

};
return shell;

>
memoizeQ :
, .
,
;
. shellQ,
(fundamental) ,
, .
shellQ,
, :
// factorial
var memfactorial = memoize(factorial, { "": 1, "1": 1 });
//
var fact6 = memfactorial(6);
var fact5 = memfactorial(5);
var fact4 = memfactorial(4);

,
,
memoize() ,
.

108

4.


shell() . ,
,
, .


, JavaScript

.
, JavaScript ,
.
for, while do-while
,
.
for-in,
.
-
, ,
.
switch ,
if-else,
.

if-else switch.

;
.
,

,
.
,

.

(Steven Levithan)
JavaScript
. , , Ajax,
, JavaScript-
HTML.
,
, , , ,
. - .
JavaScript
, .
,
, 1
,
.
,
, ,



.
1 - ,
.
(, , )
.

110

5.



.
,
(, HTML-
XML-),
.
?
, (. 5.1).
5.1.

str = "" + "b" + "";

+=

str = "";
str += "b";
str += "";

array.joinQ

str = ["a", "b", "c"].join("");

string. concatQ

str = "a";
str = str.concat("b", "c");

,
,
.

.

(+) - (+=)

, , IE7
, ,
.
,
.
.
:
str += "one" + "two";

:
1. .
2. "onetwo" .

111

3.
St .

4. str.
,
, .
(
1 2 )
str .
10-40% :
str += "one";
str += "two";

,
, :
str = str + "one" + "two";
// str = ((str + "one") + "two")

,
str,
, ,
.
(, str = "one" + str + "two"),
.
. , IE,
, ,
(. 5.1).
,

.
s1 = "one";
s2 = "two";
s3 = s2 + s1;

s1----------------------------- H

s2------------------------------H
s3------------------------------------------------------------------ )

. 5.1. :
s3 si s2;
s2

IE. IE 8
( )
IE7 .

112

5.

IE.
IE 8 ,
. (
) ,
, ,
.
IE8
-
, -
. ,
, toStringO ,
length DOM.

IE7
,
.

. IE, IE 8 ,
,


( ,
).
, largest = largest + s1 + s2
IE7
largest - , s1, s2. largest += s1 + s2, ,
,
largest . s1 + s2
,
.

Firefox

, Firefox
. , :
function foldingDemoO {
var st = "compile" + "time" + "folding";
str += "this" + "works" + "too";
str = str + "but" + "not" + "this";

}
ale rt(foldingDemo. toStringO);
/* Firefox :
function foldingDemoO {

113

var str = "compiletimefolding";


str += "thisworkstoo";
str = str + "but" + "not" + "this";

} */
,
,
. ,
, ,
,
, .
-* &

__

YUI Compressor
.
JavaScript 9.


Ar ray. prototype, join
-,
. -,
.

, , ,

IE7 .
,
,
:
var str = "I'm a thirty-five character string.",
newStr =
appends = 5000;
while (appends--) {
newStr += str;

>
5000 35 .
. 5.2 1 , IE7.
5000 ,
.
, IE7,

1 . 5.2 5.3
10 IE7, Windows ,
(: 2 Core 2 Duo; : 1 ).

114

5.

.
.

. 5.2. IE7
+=
- (
IE 8)
,
. ,
, ,
; 226 5000 -
, ,
, 32
20000
.
,
:
var str = "Im a thirty-five character string.",
strs = [],
newStr,
appends = 5000;
while (appends--) {
strs[strs.length] = str;

}
newStr = strs.join("");

. 5.3 IE7.

115


40

30

30-

20

20-

10-

10

5000

10000
15000

20000

. 5.3. IE7



.
, ,
,
.

String.prototype.concat()
concatQ
,
.
,
, .
//
str = str.concat(sl);
//
str = str.concat(s1, s2, s3);
// ,
str = String.prototype.concat.apply(str, array);

, concatQ
+ +=
IE, Opera Chrome. ,
concatQ

116

5.

, ,
( Opera)
,
+ +=, IE7
.



(
, ,
),
.

, .

. ,
, ,
, ,
, . ,

.1
- ,
.
, , , ,


.
: ,

.

,
. ,
, Regular Expressions
Cookbook2 (http://oreilly.com/catalog/9780596520694/) (OReilly),
(Jan Goyvaerts) (Steven
Levithan) ( !),
JavaScript
.
1
.
2 .
. - . . - .: -, 2009.

117



, , .
,
:
1:
(
RegExpQ)

,
. ,

.
2:

, .

lastlndex 1,
4 (- )
.
,
,
, ,
. ,
~, IE Chrome ,
,
,
. :
,
,

( , ,
Chrome).
3:

.
- ,
1 lastlndex () test()

/ (global - ).
, ,
match(), replace(), searchQ split(),
.

118

5.



.
4:
,
.
,
, 2 ,
. ,
(
) ,
.
,
.

3 - .

(
JavaScript)
. ,

.
.
,
, ,
, , ,
.

.

,
,
. 1
, .
( *, +? {2,})
,
, (
|) .

1 , [a-z],
, \s ,
,
.

119

,
,
.
,
,
.

- ,
,
,
. ,

,
.


,
.
/h(ello|) hippo/.test("hello there, happy hippo");

hello hippo
happy hippo. h,
.
(11|) .
(
) ello
.
.
, h
hippo t .
,
,
( h)
.
, ,
, ,
,
. h
, 14- ,
h happy.
. ello
,
, ,
happy hippo (. 5.4).
.

120

5.

/h(ello|) hippo/

hello there, happy hippo

14- :

/h(ello|appy) hippo/

I__ f ----------

hello there, happy hippo^,

. 5.4.


,
, .
var str = "<p>Para 1 .</>" +
"<img src=smiley.jpg>" +
"<p>Para 2.</p>" +
"<div>Div. </div>";
/<p>.*<\/p>/i.test(str);


<> .
.*. ,
, ( )
- ,
.
, !
,
,
<.
,
.
< , <
</div>. \ / (
) ,
. ,
, </>
. , -

121

, , ,
, .

, *
( ) *?.

.
/<>.*?<\/>/ .*?,
< \ / > . ,
*?
, ,
. <
,
.*?
- . ,
< \ / > ,
, .
,
,
, ,
(. 5.5).



, , , ,

. ,
, HTML .
, .
, ,
JavaScript,
, ,
[\s\S].
/<html>[\s\S]*?<head>[\s\S]*?<title>[\s\S]*?<\/title>[\s\S]*?<\/head>
[\s\S]*?<body>[\s\S]*?<\/body>[\s\S]*?<\/html>/

,
HTML,
,
. </html>, ,
[\s\S]*? , ,

,
[\s\S]*?,

122

5.

. ,
[\s\S]*?, </body>,
<\/body> ,
</body>,
. ,
,
[\s\S]*?, ..

<> 1. </>
:

/< >-_*< >/ *


12345678

/<>.^?<>/ i

11

1. <
2. <
3. <>

2. <
3. <>
4. <>
5. <>
6. <>
7. <jD>Pa
8. <>
9. <>
10. <>
11 .<>
12. <>
13. <>
14. <>
15. <>
16. <>
123

1.</>
1. </> []
1.</
1. </ []
1. </
1 .</ []
1 .<
1 . < []

1.
1.<
11</
1.</
1.</>
5678

16

1 23

4 5 6 78

4. <> [ ]
5. <> []

6. <>
7. <> []

8. <>
9. <> []
10. <>
11. <> []
12. <>
13. <> []
14. <>
15. <> []
16. <> 1
17. <> 1 []
18. <> 1.
19. <> 1.<
20. <> 1.</
21. <> 1. </
22. <> 1. </>^
123

5678

22

. 5.5.

:

,
. , ,

. .*?,

123

,
[~"\\]*, ,

, .
HTML .
,
[~<], [\s\S],
.
, ,
(
) [\s\S] ( ).

, ,
[\s\S] ,
. ,
,
:
/<html>(?:(?! <head>)[\s\S])* <head>(?:(?!<title>)[\s\S])*<title>
(?:(?!<\/title>)[\s\S])*<\/title>(?:(?!<\/head>)[\s\S])*<\/head>
(?:(?!<body>)[\s\S])*<body>(?:(?!<\/body>)[\s\S])*<\/body>
(?:(?!<\/html>)[\s\S])*<\/html>/




HTML, .
,
,
.
, ,
HTML-
, ,
. , ,
.



, .NET, Java, Onigurum a, PCRE Perl,
. - (?>. ..),
, -

.
, ,
.
,

124

5.

HTML-: [\s\S]*?
HTML- ,
HTML-
.
,

, [\s\S]*?
.
, JavaScript
,
. , ,
,
:
.1 ,
;
.
,

. , :
(?=(, ))\1

,
.
,
.
, ,
HTML-, :
/<html>(?=([\s\S]*?<head>))\1(?=([\s\S]*?<title>))\2(?=([\s\S]*?
<\/title>))\3(?=([\s\S]*?<\/head>))\4(?=([\s\S]*?<body>))\5
(?=([\s\S]*?<\/body>))\6[\s\S]*?<\/html>/

, </html>
[\s\S]*?
, , -
.

,
, .
, ,
, ,
.

1 ,

ECMAScript.

125



,
. ,
,
(, (+)*).

.

.
,
, HTML-,
:
/ < ( ? : >... ] " , ] * )*>/

, , ,
,

HTML.
, /< >]*>/,
>
.
,
,
, .

,
*.
,
.
:
,
. , +
,

-
, , - .


.

.
<,
>, ,
-

126

5.

(
) ,
<.
, . !
.
,
,
/(++)+/ , .
/+/,
,
,
.
10
(""),
+ 10 .
,
+ .
, ,
,
+ , ,
. ,
,
.
+ , - ?
+ , - ,
?
+ , - ,
? , ,
,

.
0 (2 ), - , -
. 10
1024 ,
20 . 35
, Chrome, IE, Firefox Opera
10 ( ),
34 , ,
. Safari,

( Safari
,
).

-

127

.
, /+/,

. , ,
,
,
.
,
/((?=(++))\2)+/, .



, ,

.
,
, .

.
, .

,
, . ,
,
.




.
.


.

, ,
. ,
, - (
,
), .
,

128

5.

.
(~ $)> (,
\u263A), (, [a-z] ,
\d) (\). ,

, , /one |two/,

. Firefox

, \s\s*,
\s+ \s{ 1, >.
, .



,
. ,

.
( ),
"[""]*.

, |,

.


( ,
).
.

cat|bat

[cb]at

red|read

rea?d

red|raw

r(?:ed|aw)

(l\r|\n)

[\s\S]

, (
[\s\S], [\d \D], [\w\W] [\0-\uFFFF])
(?:. |\|\| \u2028|\2029). ,
( , ,
).

129

,
(
), .
,
,
. ,

.
, Chrome Firefox
,
.



.
,
- ,
(?:...) (...).
,
.
,
, , ,
, regex.(), $&
.

Firefox,

.

,

, .
, ,
, /" ( ]*)"/

/"[''"]*"/
.
.


, ,
.
,

130

5.

, ,
-
. , /~(ab|cd)/
. , IE Chrome
,
.
/("abpcd)/,
~ , IE
,
.

, ,
, .
(
) ,
,
, .
Ope
ra 9.x ,
Opera 10.
,

,
.

,
.
,

,
, .
.
, , :
while (/regexl/.test(strl)) {
/2/.exec(str2);

>
:
var regexl = /regexl/,
regex2 = /regex2/;
while (regexl.test(strl)) {
regex2.exec(str2);

>

131


. ,
,
,
,
. ,
,
,
.



.
. , ,
. ,
, ,
:
endsWithSemicolon = /;$/.test(str);

, - , ,
,
.
. , ,
($),
. ,
. (
), .

, ,
:
endsWithSemicolon = str.charAt(str.length - 1) ==

,
, , ,
,
.
charAt(),
. slice(), substr() substring()
,

. ,
indexOfQ
lastlndexOfQ.

132

5.

,

.



. ECMAScript 5
trimQ (
), Java
Script .
trim( ) ,
.

,
,
.



trimQ, JavaScript-, . ,

: - -
.
, .
if (!St ring.prototype.trim) {
String, prototype, trim = functionQ {
return this.replace(/~\s+/. "").replace(/\s+$/, "");

}
}
// ...
//
// (\t) (\).
var str = " \t\n test string ".trim();
alert(str == "test string"); // "true"

if, ,
trimQ,
,
JavaScript.

, .
/\s+$/ /\s\s*$/
Firefox 35% (

133

)1.
, Firefox
,
.
.
, , /~\s\s*/
,
(

).
trimQ
,
, . . 5.2

trim() .

, ,
(
),
.
// trim 2
String.prototype.trim = function() {
return this.replace(/~\s+|\s+$/g,

}
, , .

/ (global - ),
, (
, ,
). ,
, ,
,
.
// trim 3
String.prototype.trim = function() {
return this.replace(/~\s*([\s\S]*?)\s*$/,

}

(
) .
.
,

1 Firefox 2, 3 3.5.

134

5.

( ),
.
*?
, [\s\S]
.
,
\s*$.
-
, ,

.
Ope
ra 9.x .
Opera 9.64 10 100
, .
Opera 10,
, .
// trim 4
String.prototype.trim = function() {
return this.replace(/~\s*([\s\S]*\S)?\s*$/, "Si);

}
,

.
,
\S. -
,
,
?.
[\s\S]*
, ,
.
,
\S
( ).
,
, , ,
. ,
, IE, Safari, Chrome Opera 10
.
,

, .
,
( - ),

135

. ,
Firefox Opera 9,

.
// trim 5
String.prototype.trim = function() {
return this.replace(/~\s*(\S*(\s+\S+)*)\s*$/, $1");

}
,
,
.
,
,
,
,
.
,
, ,
.
,
(\s+\S+) (?:\s+\S+),
20-45% Opera, IE Chrome
S afari Firefox.
. ,
,
.


,
.
:
// trim 6
String.prototype.trim = function() {
var start = 0,
end = this.length - 1,
ws = " \n\r\t\f\x0b\xa0\u1680\u180e\u2000\u2001\u2002\u2003
\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u202f
\u205f\u3000\ufeff;
while (ws.indexOf(this.charAt(start)) > -1) {
start++;

}
while (end > start && ws.indexOf(this.charAt(end)) > -1) {
end--;

}
return this.slice(start, end + 1);

136

5.

ws ,
ECMAScript 5.
- ,
.
,
,
.
,
.

,
, .
,
, .
,
:
.

,

.





.
// trim 7
String.prototype.trim = function() {
var str = this.replace(/~\s+/.
end = str.length - 1,
ws = /\s/;
while (ws.test(str.charAt(end))) {
end--;

}
return str.slice(0, end + 1);

}




(
). ,

137

.

,

.
t rim() .
, ,
,
. ,

, ,

.


.

,
;

.
. 5.2.
5.2. trim()

Trim l b Trim 2

Trim 3

()
Trim 4
Trim 5C

Trim 6 Trim 7

IE7

80/80

315/312 547/539

36/42

218/224

14/1015 18/409

IE8

70/70

252/256 512/425

26/30

216/222

4/334

Firefox 3

136/147 164/174 650/600

1098/1525 1416/1488 21/151

20/144

Firefox 3.5

130/147 157/172 500/510

1004/1437 1344/1394 21/332

18/50

27/29

541/554

2/140

5/80

32/33

510/514

<0,5/29 4/18

Firefox 3.2.3 253/253 424/425 351/359


33/31

69/68

12/205

Safari 4

37/37

Opera 9.64

494/517 731/748 9066/9601 901/955

Opera 10

75/75

94/100 360/370

46/46

514/514

2/186

12/198

Chrome 2

78/78

66/68

59/59

140/142

1/37

24/55

100/101

1953/2016 <0,5/210 20/241

100 (40 );
10
, - 1000.
/\s\s*$/.

.

138

5.




, ,
, .
,
IE7
.
, IE7 ,

.
+ += .


.

, ,

, .
, , :
,
,
,
,
.

,
,
(.
).

,
.
.



( - , ).
, ,
, ,
.

6

,
- -.
-;
,
.
,
,
- ,
.
1 ,
. ,

JavaScript-
.
,
JavaScript,
, .

,
- ,
.



,
JavaScript

140

6.

,
( ) (
- ).
,
, .
,
.
JavaScript,
, (
3). ,
.
,
:
<html>
<head>
<title>Browser Ul Thread Example</title>
</head>
<body>
<button onclick="handleClick()">Click Me</button>
<script type="text/javascript">
function handleClick(){
var div = document.createElement("div");
div.innerHTML = "Clicked!";
document.body.appendChild(div);

}
</script>
</body>
</html>


. -
, , -
handleClick() ,
, , .
, .
.

JavaScript. handleClickQ
<div> <body>,
.
JavaScript

,
JavaScript, . 6.1.
,
, .

141

,

.
- ,
, ,
,
.
,
JavaScript, ,
,
, .

handleClickQ

<div>

handleClickQ

<div>

handleClick()

. 6.1.


,
JavaScript-.

,
. :
( 4)
.

,
,
,
.
, . 6 . 2 .

142

6.

W ind ow s Internet E xplorer

Stop running this script?


A script on this page is causing Internet Explorer to run slowly.
If it continues to run, your computer may become
unresponsive.

| ........Yes'.........

Mo

. 6.2. ,
Internet Explorer 5


. ,
,
.

,
.
. ,
,

,
. ,

:
Internet Explorer 4
5
; Windows
H KEY_C U RREN T_U SER\Softw are\M icrosoft\InternetExplorer\Styles\M axScriptStatem ents.
Firefox
10 ;
( about :config
) dom .m ax_script_run_time.
S afari
5 ; ,
, Develop ()
Disable Runaway JavaScript Timer ( Runaway JavaScript
Timer).

Chrome ,
.
.

143

Opera
JavaScript,
,
, Opera,
.

,
.
,


(
).
, ,
. ,

.
, , -
, ,
, . ,

, .

- ?
,
, ,
. ,
,
, . (Brendan Eich),
JavaScript, - : [],
, - ...
- ,
JavaScript- ?
, - .
, JavaScript-,
100 . ,
(Robert Miller) 1968 .1 ,
(Jakob Nielsen),
, Usability Engineering

1 Miller, R. ., Response time in man-computer conversational transactions,


Proc. AFIPS Fall Joint Computer Conference, Vol. 33 (1968), 267-277.
: http://portal.acm.org/citation.cf m?id=1476589.1476628.

144

6.

(Morgan Kaufmann, 1994) 1,


Xerox-PARC 1991 .2
,
100 ,

. , 100 ,
.

JavaScript,
,
100 .
,
JavaScript-
. ,
,
JavaScript,
JavaScript- .
, , .
.

. JavaScript-,
,
,
.
,
, ,
.
,
, onclick .
Internet Explorer JavaScript, ,
,
. ,
, onclick
.


, 1 : wwwMseit.com/papers/responsetime.htmL
2 Card, S. ., G.G. Robertson, and J.D. Mackinlay, The information visualizer:
An information workspace, Proc. ACM CHI91 Conf. (New Orleans: 28 April2 May), 181-188. : http:// tal.acm.org/citation.cfm?id=
108874.

145

.
100 .

, (
, JavaScript,
10).


,
100 .
,

. JavaScript-
,
. JavaScript-.


JavaScript
setTimeout() setlntervalQ, :
, , ( ),
. setTimeoutQ
, , setlntervalQ
,
.


. setTimeoutQ setlnter
valQ JavaScript,

JavaScript-. :
function greetingQ{
alert("Hello world!");

}
setTimeout(greeting, 250);


greeting() 250 .

JavaScript-. , ,
,
,
; , , ,
,
. :

146

6.
var button = document.getElementById("my-button);
button.onclick = function(){
oneMethod();
setTimeout(function(){
document.getElementById("notice"),style.color = "red";
>, 250);

>;
,
oneMethodQ . ,
notice ,
250 . 250
setTimeoutQ, .
setTimeoutQ >
, ,
+ 250.
. 6.3.

0;

onclickQ

-------------- 1-------------- 1---- 1----------- 1-------

0
V, ........................................... ^

50

100
350

setTimeoutQ

. 6.3. setTimeoutf) ,
JavaScript-

, , ,
, ,
. ,
,
,
,
onclick :

147


var button = document.getElementByldCmy-button");
button.onclick = function(){
oneMethod();
setTimeout(function(){
document.getElementByldC'notice").style.color = "red";
>, 50);
anotherMethod();

>;
anotherMethodQ 50 ,
, ,
, onclick .

onclick, . . 6.4.

[ - I
onclick()

,]
J

onclickQ

onclickQ

-------------- 1--------------1------ 1------- 1---------------------------------------

0
50
100
........................................... *

setTimeoutQ

150

. 6.4. , , ,
, set Timeout (),
,

,

. ,
,
. ,
.
,
, .

148

6.

?'
9V

setlnterval() setTimeoutQ,
,
JavaScript-.
, , ,
setlnterval(), .


JavaScript
.
250 , ,
250 setTimeout().
,
.
.
Windows 15 ,
15 , ,
0 15
. 15
Internet Explorer ,
, ,
25 ( 15 30 ),
15 .

,
.

10 .


,
, , .
,
4, ,
.
, , ,
. ,
:
for (var i=0, len=items.length; i < len; i++){
process(items[i]);

}
-
processQ, items

149

. Professional JavaScript for Web De


velopers, Second Edition (Wrox, 2009),
, ,
:
?
?
,

.
:
var todo = items.concat(); //
setTimeout(function(){
//
process(todo.shift());
// ,
if(todo.length > 0){
setTimeout(arguments.callee, 25);
} else {
callback(items);

}
}, 25);

,

. setTimeout() ,
. todo.shiftQ
.
processQ.
. todo ,
. ,
, setTimeout()
arguments, callee. ,
.
, callback().

.

25 ,

.


, , .
:

150

6.
function processArray(items, process, callback){
var todo = items.concat(); //
setTimeout(function(){
process(todo.shift());
if (todo.length > 0){
setTimeout(arguments.callee, 25);
> else {
callback(items);

>
>, 25);

>
processArrayQ, , ,
,
: ,
,
.
:
var items = [123, 789, 323, 778, 232, 654, 219, 543, 321, 160];
function outputValue(value){
console.log(value);

>
processArray(items, outputValue, function(){
console.log("Done!);

>);
processArrayQ

. ,
, ,

.

. ,

, -
.
,
, - .



.
, -

151

, .
,
,

. ,
. :
function saveDocument(id){
//
openDocument(id)
writeText(id);
closeDocument(id);
// ,
updateUI(id);

}
,
,
. ,
,
:
function saveDocument(id){
var tasks = [openDocument, writeText, closeDocument, updateUI];
setTimeout(function(){
//
var task = tasks.shift();
task(id);
//
if (tasks.length > 0){
setTimeout(arguments.callee, 25);

}
}, 25);

}
tasks
. ,
, ,
, .
,
:
function multistep(steps, args, callback){
var tasks = steps.concat(); //
setTimeout(function(){

152

6.
//
var task = tasks.shift();
task.apply(null, args || []);
//
if (tasks.length > 0){
setTimeout(arguments.callee, 25);
} else {
callback();

}
}, 25);

}
multistepO : ,
,
.
:
function saveDocument(id){
var tasks = [openDocument, writeText, closeDocument, updateUI];
multistep(tasks, [id], function(){
alertf'Save completed!);

});
}
, multistepO
,
id. ,
,


.



. 1000 ,
1 .
25 ,
(25 4- 1)1000 = 26000 26 .
50
25 ? (1000/50)44425
4- 4-1000 = 1500 1,5 ,
,
50 .
, .
100 ,

JavaScript, . -

153

JavaScript 50 ,
,
,
.

Date.
:
var start = +new Date(),
stop;
someLongProcess();
stop = +new Date();
if(stop-start < 50){
alert("Just about right.");
} else {
alert(Taking too long.");

}
Date
,
, Date
. (+) Date
,
.
, .
processArrayQ
, :
function timedProcessArray(items, process, callback){
var todo = items.concat(); //
setTimeout(function(){
var start = +new Date();
do {
process(todo.shift());
} while (todo.length > 0 && (+new Date() - start < 50));
if (todo.length > 0){
setTimeout(arguments.callee, 25);
} else {
callback(items);

}
}, 25 );

154

6.

do-while
.
,
, .
Firefox 3 1000
, processQ , 38-43 ;
processArrayQ
25000 .
.



,
.
,
,
.
.
,

.
, ,
. (Neil
Thomas) Google Mobile ,
Gmail iPhone Android .1
, -
-
-.
,
,

.
( 100 200 ),
, Gmail
.
, -

.
,
.

1 http://googlecode.blogspot.comt/2009,/07/
gmail-for-mobile-html5-series-using.html.

155


JavaScript ,

.
(Web Workers API) ,
, ,
. Web
Workers API HTML 5,
(http://www.w3.org/TR/
workers/).
Firefox 3.5, Chrome 3 Safari 4.

- ,
Worker ,
JavaScript. ,
, ,
, ,
.



,
. , JavaScript-
, ,
,
.
,
DOM -
, ,
,
JavaScript.
:
navigator, : appName, appVersion, userAgent platform.
location ( , window, ,
).
self, .
importScriptsQ JavaScript-,
.
, ECMAScript,
Object, Array, Date .
XMLHttpRequest().

156

6.

setTimeoutQ setlntervalQ.
close(), .

,
JavaScript. JavaScript, ,
. ,
URL- JavaScript-:
var worker = new Worker(code.js");


. ,
,
.


-
. -
,
postMessageQ,
.
onmessage. :
var worker = new Worker("code.js");
worker.onmessage = function(event){
alert(event.data);

};
worker.postMessage("Nicholas");

message.
onmessage data,
.
-
postMessageQ:
// code.js
self.onmessage = function(event){
self.postMessage("Hello, " + event.data + "!");

};

onmessage worker.

- .
postMessageQ
: (, ,
, null undefined), Object Array;
.
,

157

.
,
,
.
.
Safari 4
postMessageQ .

,
Firefox 3.5.


JavaScript-
importScriptsQ,
URL- JavaScript-, .
importScripts() ,
.

,
. :
// code.js
importScripts("file1.js", "file2.js");

self.onmessage = function(event){
self.postMessage(Hello, " + event.data + !");

};
JavaScript-,
.



,
.
, -
,
.

JSON ( JSON
7). , ,
500 . ,
JavaScript- ,
.
,

158

6.


.
-:
var worker = new Worker("jsonparser.js");
// ,
worker.onmessage = function(event){
// JS0N,
var jsonData = event.data;
// JSON
evaluateData(jsonData);

>;
// JSON
worker.postMessage(jsonText);

,
JSON :
// jsonparser.js
// JS0N
self.onmessage = function(event){
// JS0N event.data
var jsonText = event.data;
//
var jsonData = JSON.parse(jsonText);
//
self.postMessage(jsonData);

};
, JSON.parseQ 500
,
,
.
, ,
, .
JSON
postMessageQ.
event.data onmessa
ge . JSON
postMessageQ
.
onmessage event.data.
, Fire
fox 3.5 , Safari 4 Chrome 3
.

159

-
,
. :

(
)

100 , ,

, . , ,
.


JavaScript
,

. ,
,
JavaScript, .
,
JavaScript ,
. :
JavaScript-
100 .

.
- ,
JavaScript-.

,
.

,
.
-
,
JavaScript

.
-,
.
,
.

7
Ajax

(Ross Harmes)
Ajax
JavaScript-.

.
,
.
HTTP-.

,
.

,
.


Ajax -
;
.
,
.

.

161


:
XMLHttpRequest (XHR)
<script>
<if rame>
Comet
XHR
JavaScript-
: XHR,
<script>
XHR. Comet <if rame> (
)
, .

XMLHttpRequest
,
XMLHttpRequest (XHR),
.


. (GET POST)
, , ,
,
. :
var url = /data.php';
var params = [
id=934875,
,limit=20

];
var req = new XMLHttpRequestO;
req.onreadystatechange = function() {
if (req.readyState === 4) {
var responseHeaders = req.getAllResponseHeaders(); //
var data = req.responseText;
//
// ...

}
}
req.open(GET, url + ? + p a r a m s . j o i n ( , true);
req.setRequestHeader(X-Requested-With', 'XMLHttpRequest'); //
//
req.send(null); //

162

7. Ajax

, URL- . 4
readyState ,
.

3 readyState.

:
req.onreadystatechange = function() {
if (req.readyState === 3) {
// ,
var dataSoFar = req.responseText;

}
else if (req.readyState === 4) { //
var data = req.responseText;

}
}
- ,
XHR, .
XHR ,
, IE
readyState 3,
. ,
, , XML; ,
.
, XHR

.
.
POST GET XHR.
XHR,
, , POST GET. ,

( ),
GET. GET- ,
.
POST- ,
URL- 2048
. , Internet
Explorer URL-

.

163

<script>

XHR: .
;
JavaScript <script>
source URL- .
var scriptElement = document.createElement('script);
scriptElement.src = *http://any-domain.com/javascript/lib.js';
document.getElementsByTagName(head)[0].appendChild(scriptElement);

<script>
, XHR.
.
GET - POST .
;
,
. ,
.
.
.
<script>, JavaScript.
XML-
JSON; , ,
.
var scriptElement = document.createElement('script');
scriptElement.src = 'http://any-domain.com/javascript/lib.js';
document.getElementsByTagName('head')[0].appendChild(scriptElement);
function jsonCallback(data) {
// ...

}
lib.js jsonCallback:
jsonCallback({ "status: 1, "colors": [ "#fff", "#000, "tfffOOOO" ] });

,
.
JavaScript; ,
.

,
.
<script> XHR
JSON.

. JavaScript

164

7. Ajax

, , ,
<script>,
. :
,

. ,
, .

XHR
XHR
;
, HTTP-.
( CSS, HTML,
JavaScript , base64)

,
. JavaScript-
MIME-
, .
.
:
var req = new XMLHttpRequest();
req.open(GET*, rollup.images.php*, true);
req.onreadystatechange = function() {
if (req.readyState == 4) {
splitlmages(req.responseText);

}
};
req.send(null);

.
rollup_images.php,
splitlmagesQ.

:
// base64.
Simages = (kitten.jpg, sunset.jpg, 'baby.jpg);
foreach (Simages as Simage) {
$image_fh = fopen($image, );
$image_data = fread($image_fh, filesize(Simage));
fclose($image_fh);
$payloads[] = base64_encode($image_data);

165

}
}
// .
Snewline = chr(1); // ,
// base64
echo implode(Snewline, Spayloads);



base64.
,
1 , .
splitImagesQ:
function splitlmages(imageString) {
var imageData = imageString.split("\u0001");
var imageElement;
for (var i = 0, len = imageData.length; i < len; i++) {
imageElement = document.createElement(img');
imageElement.src = data:image/jpeg;base64,' + imageData[i];
document.getElementByld(container).appendChild(imageElement);

}
}

.
, .
base64
;
URL- data: MIME- image/jpeg.
,
HTTP-. 20
100 ; ,
HTTP-.
.
JavaScript-, CSS-,
HTML .
, JavaScript-
. ,
JavaScript, CSS
, :
function handleImageData(data, mimeType) {
var img = document.createElement(img);

166

7. Ajax
img.src = 'data:' + mimeType + ;base64, + data;
return img;

}
function handleCss(data) {
var style = document.createElement(style*);
style.type = text/css;
var node = document.createTextNode(data);
style.appendChild(node);
document.getElementsByTagName(head)[0].appendChild(style);

}
function handleJavaScript(data) {
eval(data);

}

, ,
. ,
readyState 3:
var req = new XMLHttpRequestQ;
var getLatestPacketlnterval, lastLength = 0;
req.open(GET, rollup.images.php, true);
req.onreadystatechange = readyStateHandler;
req.send(null);
function readyStateHandler{
if (req.readyState === 3 && getLatestPacketlnterval === null) {
//
getLatestPacketlnterval = window.setInterval(function() {
getLatestPacket();
}, 15);

}
if (req.readyState === 4) {
//
clearlnterval(getLatestPacketlnterval);
//
getLatestPacket();

}
}
function getLatestPacket() {

167

var length = req.responseText.length;


var packet = req.responseText.substring(lastLength, length);
processPacket(packet);
lastLength = length;

}
readyState 3,
. 15
.
, -,
.

XHR ,
.
http://techfoolery.com/mxhr/.
,
, ,
, . - CSS-

,
. ,
JavaScript-.
, .
3
readyState URL- data: Internet Exp
lorer. Internet Explorer 8 ,
Internet Explorer 6 7
.
, , ,

:
,
(
), .
, JavaScript- CSS, ,
HTTP-;
,
,
.
HTTP- Ajax,

. ,
100 -

168

7. Ajax

.
,
4 10
.
, http://
techfoolery.com/mxhr/.


, .
,

, ,
.
, : XHR
.

XMLHttpRequest
XHR -
, .
GET- POST-,
HTTP-. .
XHR ,
URL-.
POST-:
var url = /data.php;
var pa rams = [
id=934875\
'limit=20'

];
var req = new XMLHttpRequestO;
req.onerror = function() {
// .

};
req.onreadystatechange = function() {
if (req.readyState == 4) {
// .

}
};
req.open(POST, url, true);
req.setRequestHeader(Content-Type, 'application/x-www-form-urlencoded);
var data = params.join(&");
req. setRequestHeader(Content-Length", data, length);
req.send(data);

169

,
. , XHR
.
,
, :
function xhrPost(url, params, callback) {
var req = new XMLHttpRequest();
req.onerror = function() {
setTimeout(function() {
xhrPost(url, params, callback);

}, 00);

};
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (callback && typeof callback === function) {
callback();

}
}
};
req.open(POST, url, true);
req.setRequestHeader(Content-Type, application/x-www-form-urlencoded);
var data = params.join( ) ;
req. setRequestHeader("Content-Length", data, length);
req.send(data);

}
XHR,
GET.
- GET-
. POST-, ,
:
, - POST-. POST-
, -,

, -, -
URL- Internet Explorer,
GET-.


<script>. JavaScript- Image,
src URL- . URL- GET-,

170

7. Ajax

-. ,
<img> DOM.
var url = '/status_tracker.php*;
var params = [
'step=2',
time=1248027314'

];
(new Image()).src = url + '? + p a r a m s . j o i n ( );

-
,
.
. ,
.

.
POST-,
,
URL-.
, .
load Image,
.
,
( ),
. , , 1,
, 2 , - .
,
204 No Content .
,
:
var url = /status_tracker.php';
var params = [
step=2\
time=1248027314

];
var beacon = new Image();
beacon.src = url + ? + params.join(
beacon.onload = function() {
if (this.width == 1) {
// .

}
else if (this.width == 2) {
// ; .

171

beacon. = function() {
// ; , .

};

.
,
.
,
.
XHR.
(, ),
.



: ,
, (
).
- .
,
. ,
, ,
- .
,

. :
, ,
JavaScript
.
,
.

XML
Ajax ,
XML.
: (
, ),
. JSON
,

XML.
,
XML:

172

7. Ajax
<?xml version="1.0" encodingsUTF-8?>
<users total="4">
<user id='T>
<username>alice</username>
<realname>Alice Smith</realname>
<email>alice@alicesmith.com</email>
</user>
<user id=,,2>
<username>bob</username>
<realname>Bob Jones</realname>
<email>bob@bobjones.com</email>
</user>
<user id="3">
<username>carol</username>
<realname>Carol Williams</realname>
<email>carol@carolwilliams.com</email>
</user>
<user id=4">
<username>dave</username>
<realname>Dave Johnson</realname>
<email>dave@davejohnson.com</email>
</user>
</users>

, XML
.
,

. , XML .
, XML
-
? -
,
?
,
XML-.
XML
JavaScript .

,
JavaScript.
,
.
XML- :
function parseXML(responseXML) {
var users = [];
var userNodes = responseXML.getElementsByTagName('users);
var node, usernameNodes, usernameNode, username,

173


realnameNodes, realnameNode, realname,
emailNodes, emailNode, email;
for (var i = 0, len = userNodes.length; i < len; i++) {
node = userNodes[i];
username = realname = email = ;
usernameNodes = node.getElementsByTagName('username);
if (usernameNodes && usernameNodes[0]) {
usernameNode = usernameNodes[0];
username = (usernameNode.firstChild) ?
usernameNode.firstChild.nodeValue :

}
realnameNodes = node.getElementsByTagName(realname);
if (realnameNodes && realnameNodes[0]) {
realnameNode = realnameNodes[0];
realname = (realnameNode.firstChild) ?
realnameNode.firstChild.nodeValue : ;

}
emailNodes = node.getElementsByTagName(email);
if (emailNodes && emailNodes[0]) {
emailNode = emailNodes[0];
email = (emailNode.firstChild) ?
emailNode.firstChild.nodeValue : ;

}
users[i] = {
id: node.getAttribute(id),
username: username,
realname: realname,
email: email

};
}
return users;

}
,
, .
XML.

<user>.
. ,
:
<?xml version=1.0" encoding='UTF-8'?>
<users total="4">
<user id="1" username="alice" realname=Alice Smith
email=alice@alicesmith.com />

174

7. Ajax
<user id="2M username="bob" realname="Bob Jones
email="bob@bobjones.com" />
<user id="3 username=carol" realname="Carol Williams"
email="carol@carolwilliams.com" />
<user id="4" username="dave" realname="Dave Johnson"
email="dave@davejohnson.com" />
</users>

XML- :
function parseXML(responseXML) {
var users = [];
var userNodes = responseXML.getElementsByTagName('users');
for (var i = 0, len = userNodes.length; i < len; i++) {
users[i] = {
id: userNodes[i].getAttribute( 'id'),
username: userNodes[i].getAttribute('username*),
realname: userNodes[i].getAttribute('realname*),
email: userNodes[i].getAttribute('email')

};
}
return users;

XPath
XPath ,
, X Path
XML-
getElementsByTagNameQ.
,

DOM.
DOM Level 3 XPath Firefox, Safari, Chrome Opera.
Internet Explorer 8 ,
.


,
XML.

XML

582960

999,4

343,1

1342,5

437960
XML

475,1

83,1

558,2

175

^ |

, 100, 500, 1000 5000 .


10
, ,
.
http://techfoolery.com/formats/, .

,

.
XML- DOM
.
XML?
,
. ,
.
,
.
XML, ,
. ,
, X Path
,
( - ,
DOM Level 3 XPath, - Internet
Explorer 8 - ).
XML ,
,
. XML
, Ajax.

JSON
(Doug
las Crockford) JSON
,
JavaScript.
JSON:
[
{ "id: 1, "username": "alice, "realname": "Alice Smith",
"email": "alice@alicesmith.com" },
{ "id": 2, "username": "bob", "realname": "Bob Jones",
"email": "bob@bobjones.com },
{ "id": 3, "username": "carol", "realname": "Carol Williams",
"email": "carol@carolwilliams.com" },
{ "id": 4, "username": "dave", "realname": "Dave Johnson",

176

7. Ajax
"email": "dave@davejohnson.com" }

]
,
,
JavaScript. , evalQ
JSON
Java
Script.
JSON, JavaScript
evalQ:
function parseJSON(responseText) {
return eval((' + responseText + ')*);

}
|
|

1>

, eval() JSON: eval() ,


JSON (
). ,
JSON. parse().

.
Firefox 3.5, Internet
Explorer 8 Safari 4. JavaScript-
JSON,
, , ,
, .
http://json.org/json2.js.
evalQ.

XML,
.
(
) :
[
{ "i:1, "u: "alice", "": "Alice Smith", "": "alice@alicesmith.com" },
{ "i": 2, "": "bob", "": "Bob Jones", "": "bob@bobjones.com" },
{ "i": 3, "": "carol", ": "Carol Williams",
"e": "carol@carolwilliams.com" },
{ "i": 4, "u": "dave", "r": "Dave Johnson", "e": "dave@davejohnson.com" }

]
, ,
, .
. -
, , ,
:
JSON.

177

[
[
[
[
[

1,
2,
3,
4,

"alice", "Alice Smith", "alice@alicesmith.com" ],


"bob", "Bob Jones", "bob@bobjones.com" ],
"carol", "Carol Williams", "carol@carolwilliams.com" ],
"dave", "Dave Johnson", "dave@davejohnson.com" ]

]

. ,
, ,
JSON:
function parseJSON(responseText) {
var users = [];
var usersArray = eval('( + responseText + )');
for (var i = 0, len = usersArray.length; i < len; i++) {
users[i] = {
id: usersArray[i][0],
username: usersArray[i][1],
realname: usersArray[i][2],
email: usersArray[i][3]

};
}
return users;

}

evalQ.
. ,
evalQ
.
JSON,
XHR.

JSON

487895

527,7

26,7

554,4

392895
JSON

498,7

29,0

527,7

JSON 292895

305,6

18,6

324,0

JSON- :
,
.
5000 ,
30% .

178

7. Ajax

JSON-P
, JSON
JavaScript,
. XHR
JSON .
evalQ
.
<script> JSON
JavaScript- Java
Script.
. JSON with padding
(JSON ), JSON-.
JSON-P:
parseJSON([
{ "id: 1, "username": "alice", "realname": "Alice Smith",
"email": "alice@alicesmith.com" },
{ "id": 2, "username": "bob", "realname": "Bob Jones",
"email": "bob@bobjones.com" },
{ "id": 3, "username": "carol", "realname": "Carol Williams",
"email": "carol@carolwilliams.com" },
{ "id": 4, "username": "dave", "realname": "Dave Johnson",
"email": "dave@davejohnson.com" }

]);
JSON-P
-,

.
JavaScript,
.

JSON, JSON-P.

JSON-P

487913

598,2

0,0

598,2

JSON-P

392913

454,0

3,1

457,1

JSON-P 292912

316,0

3,4

319,4

,
XHR, , ,
10 .
JSON- ,
- .

179

- JSON-
JSON-,
,
JSON- .
JSON-
. ,
JSON, XHR,
.
, 10000 100000
, JSON-P.

JSON-, :
JSON-
JavaScript,
-
<script>. JSON,
, Java
Script, evalQ,
XHR.
JSON-,
,
URL- cookies.

JSON?
JSON XML.

. , ,
. JSON
/
.
,
,
. -
, ,
. JSON

Ajax,
<script>.

HTML

HTML .
HTML
JavaScript,

180

7. Ajax

. , ,
, HTML
, . JavaScript- ,
innerHTML . ,
HTML:
<ul class="users">
<li class="user" id="1">
<a href="http://www.site.com/alice/ class="username>alice</a>
<span class=,,realname,>Alice Smith</span>
<a href="mailto:alice@alicesmith.com"
class="email">alice@alicesmith.com</a>
</li>
<li class="user" id="2">
<a href="http://www.site.com/bob/" class="username">bob</a>
<span class="realname">Bob Jones</span>
<a href="mailto:bob@bobjones.com" class="emair'>bob@bobjones.com</a>
</li>
<li class="user" id="3">
<a href="http://www.site.com/carol/" class=username">carol</a>
<span class="realname">Carol Williams</span>
<a href="mailto:carol@carolwilliams.com"
class="email">carol@carolwilliams.com</a>
</li>
<li class="user" id="4">
<a href="http://www.site.com/dave/" class="username">dave</a>
<span class="realname">Dave Johnson</span>
<a href="mailto:dave@davejohnson.com"
class="email">dave@davejohnson.com</a>
</li>
</ul>

, HTML
,
, XML.
HTML-, id,
class . , HTML
, ,
,
. ,
,
.
, , JSON,
,
.

,
HTML

181

CPU. ,
JavaScript .
, HTML
. - ,
,
:
document.getElementById(data-container).innerHTML = req.responseText;


HTML
. :
HTML
DOM. , HTML
,
JavaScript-.

HTML

1063416

273,1

121,4

394,5

, HTML
, , ,
. HTML
DOM ,
;
,
.
,
, HTML-,
. ,
, HTML
.


,
,
. ,
-:
Jacob;Michael;Joshua;Matthew;Andrew;Christopher;Joseph;Daniel;Nicholas;
Ethan;William;Anthony;Ryan;David;Tyler;John

- ,
, .
-,
. ,
-:

182

7. Ajax
1:alice:Alice Smith:alice@alicesmith.com;
2:bob:Bob Jones:bob@bobjones.com;
3:carol:Carol Williams:carol@carolwilliams.com;
4:dave:Dave Johnson:dave@davejohnson.com



( ,
, ).

;
split(), - .

- ,
( ,
JavaScript ). splitQ

10000 + .
:
function parseCustomFormat(responseText) {
var users = [];
var usersEncoded = responseText.split(
var userArray;
for (var i = 0, len = usersEncoded.length; i < len; i++) {
userArray = usersEncoded[i].split(':
users[i] = {
id: userArray[0],
username: userArray[1],
realname: userArray[2],
email: userArray[3]

};
}
return users;

}

.
,
.
ASCII-, ,
. ,
, ASCII- :
function build_format_custom($users) {
$row_delimiter = ch (1);

// \u0001 JavaScript.

183


$field_delimite = chr(2); // \u0002 JavaScript.

Soutput = array();
foreach (Susers as Suser) {
Sfields = array($user['id'], $user['username'], $user['realname'],
$user['email']);
$output[] = implode($field_delimiter, Sfields);

}
return implode($row_delimiter, Soutput);

}
JavaScript
(, \u0001). splitQ
, .
, ,
-;
, IE split()
, .
.
// ,
var rows = req.responseText.split(/\u0001/);
// - ( ),
var rows = req.responseText.split(\u0001");



XHR <script>:

(XHR)

222892

63,1

14,5

77,6

222912
(<script>)

66,3

11,7

78,0


- XHR
<script>. ,

.
, JSON
, .

.

184

7. Ajax


;
JSON
-.
,
:
JSON-
<script>.
, JavaScript,
.
,
.
-, XHR
<script>
splitQ.
, ,
JSON-,
.
. 7.1
(
), ,
.
HTML,
. ,
.

XML

582960

999,4

343,1

1342,5

JSON-P

487913

598,2

0,0

598,2

XML

437960

475,1

83,1

558,2

JSON

487895

527,7

26,7

554,4

JSON

392895

498,7

29,0

527,7

JSON-P 392913

454,0

3,1

457,1

JSON

292895

305,6

18,6

324,0

JSON-P

292912

316,0

3,4

319,4

(<script>)

222912

66,3

11,7

78,0

(XHR)

222892

63,1

14,5

77,6

185

Ajax

XML
JS0N-P
XML (XHR)

JSON (XHR)

JSON (XHR)
JS0N-P

JSON (XHR)
JS0N-P
(<script>)

(XHR)

200

400

()

600

800

1000

1200

1400

()

. 7.1.

,
.
,
. ,
http://techfoolery.com/formats/.


Ajax
,
.
,
,
.


Ajax- - , .
:
HTTP- ,
.
,
.

, .

186

7. Ajax

HTTP-
, Ajax-,
GET. GET- ; ,
HTTP-. Expires ,
. ,
URL-
, . ,
Expires:
Expires: Mon, 28 Jul 2014 23:30:00 GMT

Expires ,
2014 . Expires
,
, .
Expires GMT.
:
Slifetime = 7 * 24 * 60 * 60; / / 7 , .
header('Expires: ' . gmdate(D, d Y H:i:s', time() + Slifetime) . ' GMT');

,
7 . Expires
, Slifetime
. Expires,
, 10 :
Slifetime = 10 * 365 * 24 * 60 * 60; // 10 , .
header('Expires: ' . gmdate(D, d Y H:i:s', time() + Slifetime) . ' GMT');

Expires
Ajax- .
-
Ajax-
, ,
. ,
,

.
.


,
,
.
,
URL-, .
XHR,

Ajax

187

URL-
:
var localCache = {};
function xhrRequest(url, callback) {
// URL.
if (localCache[url]) {
callback.success(localCache[url]);
return;

}
// , .
var req = createXhrObject();
req.onerror = function() {
callback.error();

};
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.responseText === || req.status == 404') {
callback.error();
return;

}
// .
localCache[url] = req.responseText;
callback.success(req.responseText);

}
};
req.open("GET", url, true);
req.send(null);

}
Expires
.
.
,

. ,
,
,
, .

:

188

7. Ajax
delete localCache[/user/friendlist/];
delete localCache[/user/contactlist/*];

, -
.
,

, .

Ajax
Ajax JavaScript-.
.
,

XHR , .
, ,
.
XMLHttpRequest .
, , ,
XHR.
.
, readyState 3,
,
.
,

. JavaScript-
readystatechange, ,

( ),
- .
XMLHttpRequest
, .
,

XMLHttpRequest,
readyState. IE
.
, XHR,
( ,
YUI 2 Connection Manager):
function createXhrObject() {
var msxml_progid = [
'MSXML2.XMLHTTP.6.0',

189

'MSXML3.XMLHTTP',
Microsoft.XMLHTTP, // 3 readyState.
MSXML2.XMLHTTP.3.O // 3 readyState.

];
var req;
try {
req = new XMLHttpRequest(); // .

}
catch(e) {
for (var i = 0, len = msxml_progid.length; i < len; ++i) {
try {
req = new ActiveXObject(msxml_progid[i]);
break;

}
catch(e2) { }

}
}
finally {
return req;

}
}
XMLHttpRequest, 3 readyState,

, .
XHR

.
Ajax, ,

.


Ajax-

.
, HTML,
,
. XML
,
,
. JSON , (
, )
, XML.
, -,

190

7. Ajax


,

.
XHR
,
, ,
,
. <script>,
,
JavaScript
JSON,
.
XHR
;
,
.
Image.
, XHR
POST-.

,
Ajax-:
, JavaScript- CSS- .
Ajax
,
.

.
,
Ajax, -
.
Ajax
, -,
, -,
,
,
.
XHR
,
- .

8

,
,
. ,
.
2005 , Ajax, -
JavaScript
, -.
, , .
- JavaScript .


JavaScript

. :
evalQ, FunctionQ, setTimeoutQ
setlnterval().
JavaScript . :
var num1 = 5,
num2 = 6,
// eval()
result = eval("num1 + num2),
// Function()
sum = new Function(arg1, "arg2, "return arg1 + arg2);
// setTimeout()
setTimeout("sum = num1 + num2", 100);

192

8.
// setlnterval()
setlntervalCsum = num1 + num2", 100);


,
.
, ,
.
,
.
:
, ,
evalQ.
:
//
var item = array[0];
//
var item = eval("array[0]");

,
10000 evalQ.
. 8.1 , .
8.1. 10000
eval()

()

eval() ()

Firefox 3

10,57

822,62

Firefox 3.5

0,72

141,54

Chrome 1

5,7

106,41

Chrome 2

5,17

54,55

Internet Explorer 7 31,25

5086,13

Internet Explorer 8 40,06

420,55

Opera 9.64

2,01

402,82

Opera 10 Beta

10,52

315,16

Safari 3.2

30,37

360,6

Safari 4

22,16

54,47



/ evalQ.
FunctionQ, setTimeoutQ setIntervalQ, .

193

eval() Function()
, ,
. , setTimeout() setlntervalQ,
,
. :
setTimeout(function(){
sum = num1 + num2;
},

) ;

setInterval(function(){
sum = num1 + num2;

}, 100);



JavaScript.
JavaScript

4 eval().
.4*

Safari 4 Chrome.

/
JavaScript
, ,
.

:
//
var myObject = new Object();
myObject.name = "Nicholas";
myObject.count = 50;
myObject.flag = true;
myObject.pointer = null;
//
var myArray = new ArrayO;
myArray[0] = "Nicholas";
myArray[1] = 50;
myArray[2] = true;
myArray[3] = null;

,
. ,
,
.
, :

194

8.
//
var myObject = {
name: "Nicholas,
count: 50,
flag: true,
pointer: null

};
//
var myArray = ["Nicholas", 50, true, null];

,
,
( Firefox 3.5 ).

.



-
. :
, ,
.
.

,
.
,
.

.
. ,
, :
function addHandler(target, eventType, handler){
if (target.addEventListener){ // D0M2 Events
target.addEventListener(eventType, handler, false);
} else { // IE
target.attachEvent("on" + eventType, handler);

}
}
function removeHandler(target, eventType, handler){
if (target.removeEventListener){ // D0M2 Events
target.removeEventListener(eventType, handler, false);
} else { // IE
target.detachEvent("on" + eventType, handler);

}
}

195

DOM Level 2 Events,


addEventListener() removeEventListener(),
, Internet
Explorer. target,
, IE ,
.
.

. ,
,
. , target
DOM
, ,
. addEventListener()
addHandler(),
.

, .


-
.
,
, .
,
,
. ,
:
function addHandler(target, eventType, handler){
//
if (target.addEventListener){ // D0M2 Events
addHandler = function(target, eventType, handler){
target.addEventListener(eventType, handler, false);

};
} else { // IE
addHandler = function(target, eventType, handler){
target.attachEventC'on" + eventType, handler);

};
}
//
addHandler(target, eventType, handler);

}
function removeHandler(target, eventType, handler){

196

8.
//
if (target.removeEventListener){ // D0M2 Events
removeHandler = function(target, eventType, handler){
target.addEventListener(eventType, handler, false);

};
} else { // IE
removeHandler = function(target, eventType, handler){
target.detachEvent("on" + eventType, handler);

};
}
//
removeHandler(target, eventType, handler);

}
.

.
,
.
.
addHandlerQ removeHandler() ,
.
, ,
,

.
, .
,
.



,
, .
,
. :
var addHandler = document.body.addEventListener ?
function(target, eventType, handler){
target.addEventListener(eventType, handler, false);

}:
function(target, eventType, handler){
target.attachEvent("on" + eventType, handler);

};
var removeHandler = document.body.removeEventListener ?
function(target, eventType, handler){
target.removeEventListener(eventType, handler, false);

}:

197

function(target, eventType, handler){


target. detachEvent(on" + eventType, handler);

};
addEventListener() removeEventListenerQ
. ,
,
DOM Level 2 Events, ,
IE.
addHandler() removeHandler()
, .
,
.
,
.
,

.


JavaScript ,
.
, JavaScript
.

JavaScript,
,
. ,
,
.



JavaScript. ,
,
.
JavaScript, .
JavaScript 64- IEEE-754.

32- .
32- .
,
JavaScript
.

198

8.

, ,
,
, toStringO,
2. :
var num1 = 25,
num2 = 3;
alert(num1.toString(2)); // "11001"
alert(num2.toString(2)); // "11"

.
JavaScript :
(AND)
1 ,
1 .
(OR)
1 ,
1 .
(XOR)
1 ,
1 .
(NOT)
1 , 0
, .
, :
// (AND)
var result1 = 25 & 3; //1
alert(resultl.toString(2)); // "1"
// (OR)
var result2 = 25 | 3; //27
alert(result2.toString(2)); // "11011"
// (XOR)
var result3 = 25 " 3; //26
alert(result3.toString(2)); // "11010"
// HE (NOT)
var result4 = 25; //-26
alert(result4.toString(2)); // "-11010"

Ja
vaScript .
.

2 , :

199

for (var i=0, len=rows.length; i < len; i++){


if (i % 2) {
className = ''even";
} else {
className = "odd";

}
//

}
2
2. 32- ,
, , ,
- 1.
(AND) 1.
, (AND) 1
0 ; ,
(AND) 1 1. ,
:
for (var i=0, len=rows.length; i < len; i++){
if (i & 1) {
className = "odd";
} else {
className = "even";

}
//

}
,
50%
( ).

.
,
, .
,
,
. , ,
, 2. :
var
var
var
var
var

0PTI0N_A
0PTI0N_B
0PTI0N_C
0PTI0N_D
0PTI0N_E

=
=
=
=
=

1;
2;
4;
8;
16;

,
(OR) , :
var options = 0PTI0N_A | 0PTI0N_C | 0PTI0N_D;

200

8.


(AND). 0,
, :
// ?
if (options & 0PTI0N_A){
//

}
// ?
if (options & 0PTI0N_B){
//

}
, ,
, , ,
.
,
,
.

JavaScript
( ), ( ) > (
).


,
, ,
JavaScript. : , , , C++.
,
,
JavaScript.


JavaScript,
Math. Math ,
.
:

Math.E

Math.LN10

10

Math.LN2

Math.L0G2E

Math.L0G10E

Math.PI

Math.SQRT1_2

]/2
2

Math.SQRT2

201

,
.
:

Math.abs(/7iy/7?)

Math.exp(/7iy/77)

Math.E"

Math.log(fliy/7?)

Math. povi(num, power)

numpower

Math.sqrt(fliy/7?)

Math.acos(x)

Math.asin(x)

Math.atan(x)

Math.atan2(y,x)

Math.cos(x)

Math.sin(x)

Math.tan(x)

,
JavaScript.
,
Math.
,
DOM CSS-.
CSS- JavaScript
JavaScript- jQuery.
jQuery ,
.
querySelectorQ querySelectorAllQ
10 ,
JavaScript .1

1 SlickSpeed http://www2.webkit.org/perf/
slickspeed/.

202

8.

JavaScript-
, .
, ,
DOM.

, .
*#*
Chrome
JavaScript. Chrome
,
JavaScript,
.


JavaScript
, .
-
, ,
.
, :

evalQ FunctionQ. ,
setTimeoutQ setlntervalQ ,
.
.
,
.
.

,
.

,
.
,
JavaScript. ,
.
,
,
,
.

JavaScript

(Julien Lecomte)
, Exceptional Perform an
ce Yahoo! 2007 , 40-60% Yahoo!
20 %
(http://yuiblog.com/blog/2007/01/04/performanceresearch-part-2/). , ,
Search Yahoo!,
(Steve Souders) Google,
, 15% -
.

- JavaScript-.
, ,
, .
,
,
.
-
- JavaScript. ,
, Apache Ant -
, Java,
.

204

9.


, 5.

Apache Ant
Apache A nt 0http://ant.apache.org/ ) -
. make,
Java
XML-, make
Makefile. A nt - Apache Software Founda
tion (http://www.apache.org/licenses/ ).
A nt make
. A nt
,
.
A nt XML
build.xml.

. .
- ,
. A nt
.
,
Java Ant.
.
.
property A nt.
, ${ }.
.
(dist) Java,
, JAR.
<?xml version="1." encoding="UTF-8"?>
<project name="MyProject" default=*dist basedir=".">
<!-- -->
<property name="src location=,,src,,/>
<property name="build" location="build'7>
<property name=dist location="dist"/>
<target name="init">
<!-- -->
<tstamp/>
<!-- -->
<mkdir di="${build}/>
</target>

JavaScript-

205

<target name="compile" depends=init" description=compile the source">


<!-- java- ${src} ${build} -->
<javac srcdir="${src} destdir="${build}"/>
</target>
<target name="dist" depends="compile
description="generate the distribution'^
<!-- -->
<mkdir dir="${dist}/lib'7>
<!-- ${build} MyProject-${DSTAMP}.jar -->
<jar jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${build}"/>
</target>
<target name="clean" description="clean up">
<!-- ${build} ${dist} -->
<delete dir=,,${build}'7>
<delete dir=${dist}7>
</target>
</project>

Apache
Ant,
. Rake
(http://rake.rubyforge.org/)>
. Rake - Ruby,
make.
Rakefile (
Makefile, Rake),
Ruby
.

JavaScript-
Exceptional Performance
Yahoo!, , ,
- - ,
, - -,
(http://yuiblog.com/blog/2006/
ll/28/performance-research-part-l/).
,
,
.
-
JavaScript-: ,

-,
, -,
.

206

9.

CNN (http://www.cnn,com/)> ,
Prototype Script.aculo.us.
12 20
.
, ,
JavaScript-
HTTP-, .
Apache Ant
concat. ,
JavaScript-
.

filelist fileset. ,
Ant:
<target name="js.concatenate^
<concat destfile="${build.dir}/concatenated.js">
<filelist dir="${src.dir}"
files="a.js, b.js7>
<fileset dir=${src.dir}"
includes="*.js"
excludes="a.js, b.js"/>
</concat>
</target>

concatenated.js ,
a.js b.js
, ,
.
: -
( )
,
.
, A nt fixlastline

:
<concat destfile="${build.dir}/concatenated.js" fixlastline="yes">
</concat>

JavaScript-
- ,
,
(, ).
, ,
().

JavaScript-

207

; ,
,

.
- http:/lru.wikipedia.org/wiki/

JavaScript-
-, ,
, , .
- ,
JavaScript,
, ,
,
,
JavaScript.
JavaScript,
(). ,
Ant:
<target name="js.preprocess" depends=js.concatenate^
<apply executable="cpp" dest="${build.dir}">
<fileset dir="${build.dir}"
includes=concatenated. js"/>
<arg line=-P -C -DDEBUG"/>
<srcfile/>
<targetfile/>
<mapper type=glob"
from="concatenated. js"
to="preprocessed.js"/>
</apply>
</target>

, js.concatenate,
preprocessed.js ,
.
,
- ( ) - (
). DEBUG.

(#define, #undef) (#if, #ifdef,
#ifndef, #else, #elif, #endif) JavaScript-,
( )
:
#ifdef DEBUG
(new YAHOO.util.YUILoader({
require: [/profiler],
onSuccess: function(o) {

208

9.
YAHOO.tool.Profiler.registerFunction(/foo, window);

}
})).insert();
#endif

,
,
(LF) UNIX.
f ixcrlf
Ant.
,
, ,
Java
Script,

. include.js:
#ifndef _INCLUDE_JS_
define _INCLUDE_JS_
#ifdef DEBUG
function assert(condition, message) {
// , alert
// message, , .

}
#define ASSERT(, ...) assert(x, ## __VA_ARGS__)
#else
define ASSERT(x, ...)
#endif /* DEBUG */
#endif /* _INCLUDE_JS_ */

JavaScript:
include "include.js"
function myFunction(arg) {
ASSERT(YAHOO.lang.isString(argvar), "arg should be a string");
#ifdef DEBUG
YAHOO.log("Log this in debug mode only");
#endif

}
,
,
DEBUG, .

.

209

JavaScript-

JavaScript-
JavaScript- - , JavaScript- , .
.
,
.

.
JavaScript- JSMin (http://www.crockford.com/javascript/
jsm in.htm l), (Douglas Crockford).
-
, JavaScript
. ,
YUI Compressor (http://developer.yahoo.com/yui/compressor/ ),

, .
YUI Compres
sor :
(-, ) , gzip-.
,
(, foo[bar] foo.bar).
, ,
, (, CfooVbar"}
{foo:"bar}).
(,
aaaVbbb' "aaabbb").
(, foo+ bar" foobar ).
JavaScript- YUI Compressor
, JSMin, - .
YUI ( 2.7.0 http://developer.yahoo.com/yui/):
Raw yahoo.js, dom.js event.js
yahoo.js, dom.js event.js + JSMin
yahoo.js, dom.js event.js + YUI Compressor

192164
47316
35896

, YUI Com
pressor, 24% , ,
JSMin. ,
.
/, ,

210

9.

,
evalQ ( FunctionQ
setTimeoutQ setlntervalQ
), wit h JScript, .
, selected
DOM (220 ):
function toggle (element) {
if (YAHOO.util.Dom.hasClass(element, ,,selected,,)){
YAHOO.util.Dom.removeClass(element, "selected");
} else {
YAHOO.util.Dom.addClass(element, "selected");

}
}
YUI Compressor ,
(147 ):
function toggle(){if(YAHOO.util.Dom.hasClass(a,"selected")){
YAHOO.util.Dom.removeClass(a,"selected")}else{YAHOO.util.Dom.
addClass(a,"selected")}};

, YAHOO,
util. Dom
' selected, (232 ):
function toggle (element) {
var YUD = YAHOO.util.Dom, className = "selected";
if (YUD.hasClass(element, className)){
YUD.removeClass(element, className);
} else {
YUD.addClass(element, className);

}
}
YUI Compressor
(115 ):
function toggle(a){var c=YAH00.util.Dom,b="selected";if(c.hasClass(a,b)){
c.removeClass(a, b)}else{c.addClass(a,b)}};

33% 48%,
,
. , gzip-,
,
; ,
gzip-.
, .
,
- , ,
.

211

,
,
, gzip- (
).
2009 Google
Closure Compiler (http://code.google.com/closure/compiler/).
, YUI Compressor,
. Closure Compiler

.
,

. , ,
. Closure
Closure Inspector Firebug (http://code.google.
com/closure/compiler/docs/inspector.html\
.
Firefox,
,
,
, ,
.



, -

, . -
,

.
: ,
, .
Apache A nt
, ,
,
,
.

JavaScript-
- ,
HTTP- Accept-Encoding ( /1.1),

212

9.

.


.
Accept-Encoding : gzip, compress, deflate identity (

(Internet Assigned Numbers Authority, IANA)).
- ,
-
HTTP- Content-Encoding.
gzip .
70%,
-.
, gzip-
, JavaScript-.
, PDF-,
, ,

.
, - Apache (, ),
gzip-
mod_gzip ( Apache 1.3, http://www.schroepl.net/projekte/mod_gzip/), mod_deflate ( Apache 2).
, Search
Yahoo! Google, , 15%
, - ,
.
HTTP- Accept-Encoding ,
-,
. gzip- -,

.
JavaScript- ,
gzip-,
(
).
Packer (http://dean.edwards.name/packer/) - JavaScript-,
(Dean Edwards). Packer
JavaScript- , YUI Compressor.
, jQuery (
1.3.2, http://www.jquery.com/):
jQuery
jQuery + YUI Compressor

120180
56814

213

JavaScript-
jQuery + Packer

39351

jQuery + gzip

34987

jQuery + YUI Compressor + gzip


jQuery + Packer + gzip

19457
19228

gzip- jQuery,
Packer YUI Compressor,
. , Packer,
( 200 300
). YUI Compressor gzip-
. Packer
,
gzip-,

.
JavaScript-
.

JavaScript-
HTTP-
-. ,
- Yahoo! (http://www.yahoo.com/ )
90% HTTP-
83% , .
(
onload)
2,4 0,9 (http://yuiblog.eom/blog/2007/01/04/performance-research-part-2/).
,
, JavaScript-.
,
, - -
Expires. RFC 1123.
: Expires: Thu, 01 Dec 1994 16:00:00 GMT.
, - Expires
, .
HTTP 1.1 RFC (RFC 2616, 14.21), -
Expires ,
.
- Apache,

ExpiresDefault.
, JavaScript-
CSS:
<FilesMatch "\.(jpg|jpeg|png|gif|j s |css|htm|html)$">

ExpiresActive on

214

9.
ExpiresDefault "access plus 1 year"
</FilesMatch>

,
, . , - Safari
iPhone , 25
(http://yuiblog.com/blog/2008/02/06/iphone-cacheability/ )
15 iPhone 3.0 OS.
HTTP-
.

, ,
JavaScript-.
,
, HTML 5 Fi
refox 3.5, Safari 4.0 iPhone iPho
ne OS 2.1.
, .
manifest <html> (
D0CTYPE, HTML 5):
<!DOCTYPE html>
<html manifest="demo.manifesto

,
,
MIME- text/cache-manifest.
- -
W3C: http://www.w3.org/TR/html5/offline.htmL

,

,
: ,

.
.

. .
.
A nt. JavaScript, yyyyMMddhhmm:
<target name="js.">
<!-- -->
<tstamp/>

215

<!-- JavaScript-, -->


< todir=${build.dir},>
<fileset dir="${src.dir}" includes="*.js"/>
<globmapper from="*.js" to="*-${DSTAMP}${TSTAMP}.js/>
</copy>
</target>

(Content Delivery Network, CDN) , ,


.
CDN - , ,
, . ,
, CDN
.

CDN,
CDN, Akamai Technologies (http://www.akamai.com/) Limelight Networks (http://www.limelightnetworks.com/).
CDN

.
, JavaScript-
CDN. , YUI
Yahoo! ( : yui.yahooapis.com,
: http://developer.
yahoo.com/yui/articles/hosting/), jQuery, Dojo, Prototype,
Script.aculo.us, MooTools, YUI CDN
Google ( : ajax.googleapis.com,
http://code.google.com/apis/ajaxlibs/).

JavaScript-
JavaScript-pecypcoB

.

CDN.
Apache A nt
.

FTP SCP.

216

9.

scp,
.
:
<apply executable="scp" failonerror="true" parallel=,,true">
<fileset dir=${build.dir} includes="*.js/>
<srcfile/>
<arg line=${live. server} :/var/www/html/7>
</apply>

, ,
SSH,
SSHEXEC ssh
, ,
- Apache UNIX:
< executable="ssh failonerror="true>
<arg line="${live.server}7>
<arg line="sudo service httpd restart"/>
</exec>

JavaScript-

, -
-
.

. , ,
,
-. ,
,
-
.
smasher - , 5
, Search Yahoo!.
JavaScript-,
.

-.
, http://github.com/jlecomte/
smasher, :
smasher.php

.
smasher.xml

JavaScript-

217

smasher

.
smasher_web.php

-.
smasher XML- ,
, ,
.
:
<?xml version="1." encoding="utf-8"?>
<smasher>
<temp_di r>/tmp/</temp_di r>
<root_dir>/home/jlecomte/smasher/files/</root_dir>
<java_bin>/usr/bin/java</java_bin>
<yuicompressor>
/home/jlecomte/smasher/yuicompressor-2-4-2.jar</yuicompressor>
<group id="yui-core">
<file type="css" src="reset.css />
<file type="css" src="fonts.css" />
<file type="js" src="yahoo.js" />
<file type="js" src="dom.js" />
<file type="js" src="event.js" />
</group>
<group id="another-group">
<file type="js" src="foo.js" />
<file type="js" src="bar.js" />
<macro name="DEBUG" value="1" />
</group>

</smasher>

group JavaScript- / CSS-. root_dir ,


. group
.
smasher
.
,
. ,
, JavaScript YUI:
$ ./smasher - smasher.xml -g yui-core -t js

,
, (

218

9.

: yui-core), ,
(, yui-core-200907191539.js).
smasher
- ,
smasher_web.php -
URL-:
http://<host>/smasher_web.php?conf=smasher.xml&group=yui-core&type=css&nominify

URL- JavaScript CSS-



.



,
JavaScript.
:
JavaScript-
-.
JavaScript- YUI Compressor.
JavaScript- (
gzip-).
JavaScript-
HTTP-
.
CDN
JavaScript-; CDN
, ,
.

, Apache Ant,
, .
,
-
,
JavaScript.

10

(Matt Sweeney)

.
-
,
-.
, :


.

, ,
, ,
.
-
, -
.
- ,

, .

;
. ,
,
-

220

10.

. ,
,
,
, .
,


.
, ,
.
,
,
.

-. ,
, ,
, ,
. ,
,
.

JavaScript-
,
JavaScript, .
Date .


. Date
,
Date .
,
( 3
DOM):
var start = new Date(),
count = 10000,
i, element, time;
for (i = 0; i < count; i++) {
element = document.createElement (div');

>
time = new Date() - start;

alert(created + count + in + time + 'ms');


start = new Date();

for (i = 0, i < count; i++) {

221

YUI Profiler
element = element.cloneNode(false);

>
time = new Date() - start;

alert('created + count + ' in ' + time + 'ms');

,
, .
Timer,

.
var Timer = {
_data: {},
start: function(key) {
Timer._data[key] = new Date();

},
stop: function(key) {
var time = Timer._data[key];
if (time) {
Timer._data[key] = new Date() - time;

>
getTime: function(key) {
return Timer._data[key];

}
>;
Timer.start(createElement);
for (i = 0; i < count; i++) {
element = document.createElement(div');

}
Timer.stop(createElement);
alert( created ' + count + ' in ' + Timer.getTime(createElement);

, Timer
, ,

JavaScript. Timer
,
.

YUI Profiler
YUI Profiler 0http://developer.yahoo.com/yui/profiler/ ),
(Nicholas Zakas),
JavaScript, Java-

222

10.

Script.
, ,

.

.
YUI Profiler ,
,

.
var count = 10000, i, element;
Y .P rofile r.sta rt( reateElement);

for (i = 0; i < count; i++) {


element = document.createElement('div');

>
Y.Profiler.stop('reateElement);
alert('created ' + count + ' in +
Y.Profiler.getAverage('createElement') + 'ms');

, ,
Date Timer,
, ,
.
,
.

.
,
. ,
initUI() 2, :
Y.Profiler.registerFunction("initUI");


.
, registerFunction()
. , , uiTest,
initUI() uiTest .testl () uiTest .test2().
:
Y.Profiler.registerFunction("testl", uiTest);
Y.Profiler.registerFunction("test2", uiTest);

,
.

223

YUI Profiler

registerObject()
:
Y.Profiler.registerObject("uiTest", uiTest);

(
), - .
uiTest.
, ,
. YUI Profiler -,
:
Y.Profiler.registerConstructor("MyWidget", myNameSpace);


myNameSpace.MyWidget.
:
var initUIReport = Y.Profiler.getReport("initUI");

,
,

.
.
:
{
min: 100,
max: 250,
calls: 5,
avg: 120,
points: [100, 200, 250, 110, 100]

>;

. Profiler
:
var uiTestlReport = {
calls: Y.Profiler.getCalls("uiTest.test 1"),
avg: Y.Profiler.getAvg("uiTest.testl")

};

,
.
:
var uiTestReport = Y.Profiler.getReport("uiTest");

224

10.

{
test1: {
min: 100,
max: 250,
calls: 10,
avg: 120

>,
test2:
min: 80,
max: 210,
calls: 10,
avg: 90

>
>;

,
.
.
,
, , ,
.
,
, :
var fullReport = Y.Profiler.getFullReport(function(data) {
return (data.calls > 0 && data.avg > 5);

>);
, ,
,
.
,
,
:
Y.Profiler.unregisterFunction("initUI"):
Y.Profiler.unregisterObject(uiTests"):
Y.Profiler.unregisterConstructor("MyWidget);

clearQ ,
.
:
Y.Profiler.clearCinitUI");

, :
Y. Profiler. clearO;

JSON,
.
- HTML-.

225

,
. ,

.
,
, ,
.
YUI Profiler ,
.
-,
:
var instrumentedFunction =
Y.Profiler.instrument"anonymousl", function(num1, num2){
return num1 + num2;

>);
instrumentedFunction(3, 5);


,
, :
var report = Y.Profiler.getReport("anonymous1");



-
.
JavaScript,

.
, .

.
:
myNode.onclick = function() {
myApp.loadData();

>;
:
myApp._onClick = function() {
.loadData();

>;
myNode.onclick = myApp._onClick;

226

10.

onclick. ,

.
,
,
:
myNode.onclick = function myNodeClickHandler() {
myApp.loadData();

};

:
var onClick = function myNodeClickHandler() {
myApp.loadData();

};
>

. ,
,
.

. .
___ fj

Firebug
Firefox
, Firebug (
http://www.getfirebug.com,/)>
(Joe Hewitt), zilla Foundation.
-,
.
Firebug
, DOM
,
DOM JavaScript- .
,
. ,
Firebug ,
.

227

Firebug


Firebug Conso
le (), . 10.1.
JavaScript,
. ,
,

, .
88
Clear

Console ] HTML

CSS

5cript

DOM

Net

Q,

offl

Profile

>

. 10.1. Console Firebug


Profile (
), Profile (
), . . 10.2 ,
.
Calls ()
, Own Time ( ) ,
, Time () ,
,
. ,
Console ()
.
'
||
Console {HTML CSS Script DOM Net PageSpeed PageSpeedActivity YSiow Q
Clear Prohle
P
r
o
f
i
l
e<451.709ms,44063c
a
l
l
s
)
Function
Calls Percent OwnTime Time
Avg
Min

F
i
l
e
oZO
combo?me..0.1.32.js(
l
i
n
e8
)
1
8.6
69
6 39.106ms 43.89ms 43.89ms 3.89ms 43.89ms
150 7.31% 33.015ms 34.767ms 0.232ms 0.009ms 30.766ms
arcade.O1.98js(
l
i
n
e4
)

3337 5.% 25.588ms 2S.588ms 0.008ms 0.001ms 0.308ms


arcade-s.-_01Ojs(
l
i
n
e2
)

143 3.77X 16.783ms 30.005ms 0.21ms 0.089ms 0.58ms


arcade0.198Js(
l
i
n
e4
)
K)
a<iwbv&}bj
3.62* 16.331ms 19.708ms 19.708ms 19.7Q8rru 19.708ms
ad_eowl
.
l
,
J
s(
l
i
n
e5
)
1
67 304* 13.748ms 33.157ms 0.495ms 0.036ms 3.716ms
arcade-$

.
_
0
.
1
.
0
.
]
(
l
i
n
e2)

arcade.01.98J'(
l
i
n
e4
)
1092 2.8896 13.026ms 27.557ms 0.025ms 0.015n 0.524ms

1104 2.6796 12.076ms 12.076ms 0.011ms 0.006ms 0.35ms


arcade0.198js(
l
i
n
e4
)

5
2
9
0
2
5
4
9
6
1
1
.
4
6
9
m
s
0
.
0
0
2
m
s
0
.
0
0
1
m
s
1
1
.
4
6
9
m
s
0
.
0
8
5
m
s
a
r
c
a
d
e
0
1
.
9
8
j
s
(
l
i
n
e
4
)

286 2.47% 11.153ms 35.975ms 0.126ms 0.04ms 0.322ms


arcade01.98js(
l
i
n
e4
)

734 2.1696 9.748ms 10.71Sms 0.015ms 0ms


f
0.313ms
arcade-s~_010
.
j
s(
l
i
n
e2
)
2354 3.79% 8.084ms 27.905ms 0.012ms 0007ms 0.153ms
arcade.O1.98js(
f
i
n
e4
)

207 1
.
7
5
9
6 7.903ms 115.32ms 0.557ms 0.023ms 14.992ms
arcade0.1.98js(Ime4
)

7
3
1
.
5
7
%
7
.
0
8
4
m
s
7
1
.
8
9
6
m
s
0
.
9
8
5
m
s
0
.
1
9
9
m
s
4
.
7
7
4
m
s
a
r
c
a
d
e
0
.
1
.
9
8
j
s
(
f
i
n
e
4
)

l
*
Y
\

"
*
/
1#
1

#
>

. 10.2. Profile Firebug

228

10.


, Firebug
Java
Script.
.
,
.
console.profile("regexTest");
regexTest(/foobar', /foo');
console.profileEnd();
console.profile("indexOfTest");
indexOfTest(/foobar, /foo);
console.profileEnd();



, ,
.
,
. , ,
profileEndQ,

. ,
, ,
profileEndQ setTimeoutQ,
.
__
1<


Firebug.

,
, ,
,
. ,
,
.
YUI Profiler, console.timeQ
Firebug
, .
,
, :
console.time("cache node");
for (var box = document.getElementById("box),
i = 0;
i < 100; i++) {

value = parseFloat(box.style.left) + 10;


box.style.left = value + "px";

>
console.timeEnd("cache node");

Console (
).
.
. ,

style ,
:
console.time("cache style");
for (var style = document.getElementById("box").style,
i = 0;
i < 100; i++) {
value = parseFloat(style.left) + 10;
style.left = value + "px";

>
console.timeEnd("cache style");




.

,
, .

Net
,

. Firebug
Net (), . 10.3.


.
, ,
( DNS,
. .). ( )
, DOMContentLoaded.
, DOM
. ()
, window load,
, DOM
. ,

230

10.


.
. 10.3 .
,
,
. ,
, ,
,
,
. ,
,
. .
4?
U
Console HTML CSS Script DOM Net~ PageSpeed PageSpeedActivity YSlow Q,
Clear : A
ll HTML CSS *HR images Flash
Netpanelactivated.Anyrequestswhilethenetpanelis inactivearenotshown.
CCTad_eo_i.lJs
{
L y m g .c o m
5SJB I 30ms
5S3t
Lyimgcom
,1 9 m $
ad.eo.l.l.js
200 06
2 O K
17m *
Lyimg.com
arcadeseed.
SKB
4m s
2 0 0 OK
Lyimg.com
bc_2.0.4.js
9S0B
>00 OK
j 68m s
arcade.O1.98
1ytmg.com
37KB
6m s
2Q 0 O K
Lytmg.com
37KB
combo?metro
6requests
83

1.62s

Puc. 10.3. Net Firebug

Internet Explorer
8 Internet Explorer
, .
IE 8 ,
.
Firebug, IE

, ,
.
,
. IE
,
,
Fiddler, .
http://msdn.microsoft.com/enus/library/dd565628(VS.85).aspx.
IE 8 (Tools
()>Developer Tools ( )).
Start Profiling ( )
J a v a S c rip t -

231

Internet Explorer

. Stop Profiling (
) ( , )
.
F5 ,
Shift-F5 .
: ,
, ,
.

(. 10.4). IE
, .
File Find Disable View Outline Images Cache Took Validate

Browser Mode: IE8 Compat View Document Mode: IE7 Standards


HTML JCSS 1Script Profiler j

c5 x

| Search Profiler

Start Profiling | CurrentView: |CalTiee


(Report 1
k l^ U I
d
Count]
InclusiveTL " I i
Function
.............
1
)
j ! !
irj Function,apply
906.25
2
! I
906.25
2
q
2
906.25

I
!! i iI
2
906.25
E3 Functioncall
2
906.25
;

!
I
_
2
484.38
:
;
Ev
iI
: !i II
JScript *wndowsa*y bbck
2
484.38
: f
3 FurKbonappJy
2
484.38
t
j- i i
S JScnpl - wndowscript block
2
484.38
;
ill
H Function.apply
484.38
2
I
I! i
E updateAccessibilityMsg
2
484.38
;
-I ;
3 JScrpt windowscript
2
484.38
l
--i- ]
2
484.38
5 Functionapply
i.
! i
^2
1 !!*111
j
StringtoUp
2
0.00
( 4 4 ! j j

Puc. 10.4. IE8


,
.

IE
JavaS cript-.

, , String::indexOf()
RegExp::test() HTML-
className, :
var count = 10000,
element = document.createElement(/div'),
result, i, time;

232

10.
element.className = /foobar';
for (i = 0; i < count; i++) {
result = foo/. test(element.className);

}
for (i = 0; i < count; i++) {
result = element.className.search(/~foo/);

}
for (i = 0; i < count; i++) {
result = (element.className.indexOf(/foo') === 0);

}
, . 10.5, ,
. ,
. ,
- ,

. ,
-
.
IE
,
.
console.time() console.timeEndQ Firebug,
IE.
if (console && !console.time) {
console..timers = {};
console.time = function(name) {
console._timers[name] = new Date();

};
console.timeEnd = function(name) {

var time = new Date() - console._timers[name];


console.info(name +
' + time + 'ms');

};
}
File Find Disable View Outline Im ages Cache Tools Validate
Browser Mode: IE8 Document Mode: IE8 Standards
HTML

CSS

Script

Profiler

Start Profiling |

Current View

&

Search Profiler

|Report 5

zl

Function
|| Count | Exclusive Time (ms) | Avg Time (ms) | Max Time (ms) | Min Time (ms) | URL
000
!String. indexOf 30,000
15.63
15.63
0.00
RegExp, test 30.000
93.75
000
15.63
0.00
String, search 30.000
125.00
000
15.63
0.00

Puc. 10.5.

- Safari

233

IE8
.csv, Export Data ( ).

- Safari
4 Safari
,
-.
Internet Explorer, -

.
,
Firebug, Resource () .
-,
Develop (). Develop (
), Preferences ()^Advanced (
) Show Develop menu in menu bar (
). - Develop ()>Show Web Inspector (
-) Option-Command-I
(Mac OS) Ctrl-Alt-I (Windows).

Profiles
Profiles () Profiles (),
. 1 0 .6 . Profiles (
), Enable Profiling (
).
Start Profiling ( ) ( ,
). ,
Stop Profiling ( ) (
, ).
**

/
Option-Shift-Command-P (Mac OS) Ctrl-Alt-P (Windows).

__ 1

Safari Firebug
(console.prof ile(), console.timeQ ),
.
, Firebug,

.

234

10.

Q,

St*

6.39s
59.176m*
56.304ms
56.304ms
56.304ms
56.304ms
2.872ms
58.071ms
58.071ms
S8.071ms
58.07lm s
58.071ms
58.071ms
58.071ms
58.071ms
58.071ms
58.07lm s
58.071ms
52.771ms
31.203ms
29.163ms

Total
7.36s
59.338ms
56.424ms
56.424ms
56.424ms
56.424ms
2.914ms
60,393 ms
60.393ms
60.393ms
60 393 ms
60.393ms
60.393 ms
60.393ms
60.393ms
60.393ms
60.393ms
60.393 ms
S2.771ms
31.362 ms
29.163ms

Average
6.39s
19.725ms
28.152ms
28.152ms
28.152ms
28.152ms
2.872ms
1.815ms
1.815ms
1.815ms
1.815ms
1.815ms
1.815ms
1.815ms
1.815ms
1.815ms
1.815ms
1.815ms
0.292ms
15.601ms
0.435ms

Calls
1
3
2
2
2
2
1
32
32
32
32
32
32
32
32
32
32
32
181
2
67

0*1v S

Function
(program)
fjet_cookie
(anonymous function)
TM
(anonymous function)
(program)
(anonymous function)
getBuddylnfo

rQjtvbn.1)
n b s ?
1S i

?fi

(anonymous function)
u&A&ZS
a
c
SWHfcffJi
(anonymous functl ..JLCKfcflJSS
v (anonymous fu corr.oo.45l
lanonymous mr,!)''?.
V
tsmPSLlO,
(program)
(program)
evaluate
sendSubscribe
appendChild

..
..

. 10.6. Profiles - Safari

console, prof ileEndQ.


,
.

Safari : Heavy (bottom-up) (


(-)), , Tree (topdown) ( (-)), .
Heavy (bottom-up) ( ()), ,
,
. Heavy (bottom-up), Tree (topdown) ( (-))
.
, ,
.
S afari
displayName.
. ,
f:
var

foo = function() {
return /foo!';

};
console.profile(/Anonymous Function');
foo();
console.profileEnd();

235

- Safari

. 10.7,
. URL-
.
Elements

jmj Resources

Scripts [ w
Self

Profiles j

Q, St.ifch Pro* s

Databases

Average

Calls

Function

(anonymous function)

.non.turn* s

Puc. 10.7. Profiles -

displayName
.
, .
var foo = function() {
return /foo!';

};
foo.displayName = /i am foo';

. 10.8, displayName
.
Webkit. ,
- ,
. ,

,
:
var foo = function foo() {
return /foo!';

};
Elements

Resources

' J%

E H

. .....

Scripts \ ^
Self
273X]

Profiles J
Total
273

Heavy (Bottom Up)

$|

Databases

Average
27JK

Calls

i c 1

[ q , Scorch froH
Function
1am foo

,vwn hui\ S

Puc. 10.8. displayName Profiles


-

236

10.

Resources
Resources () , Safari
. Net
() Firebug, ,

1.
. Resources () -
,
,
(. 10.9).

, Size
RESOURCES

SW *

ll.iii

I? 71*

15.51,

23 M t

<> http://fn.www.yahoo.com/

arcade_0.1.3 css
combo

I yn*$ tom/

ad^eojl.lj
Jyim g com /d/a/1-/jva prom ..

page_bg_slate._070609.9if
d yi*n;

p.gif
yirvg
'

turn event

yahooJogo_us_061509.p...
I yimg toro/a/i/ww/met

gspnte_pg_slate_062209....

<1yimy

I Iarcade-seed_0.1.0.js
I

| l.yimg / / fib/

Puc. 10.9. Resources () Safari

, , , Safari 4
, .
S afari ,
. ,
,
HTML;
, ( 1).

1 Safari 5 Net (). - .


.

237

Chrome

Chrome
Google Chrome
,
- W ebKit/Safari.
Resources () Chrome
Timeline ( )
. Chrome
Profiles () -,
.
Safari, Chrome

, Firebug,
c o n s o le .p ro file () console.tim e().
. 10.10, Timeline ( )
,
: Loading (), Scripting () Rendering
().
.
Records (),
.
,Resources
[

RECORDS
0P
a
i
n
t(377x11)
Q TimerF
i
r
e
d(19S)
0P
a
i
n
t<171*40)
0 SendRequest(
.
.
.
0 SendRequest{
.
.
.
TimerF
i
r
e
d(223)
Layout
%P
a
i
n
t(63x407)
TimerF
i
r
e
d(224)
$SendRequest{
.

SendRequestf
0SendRequestU
.
.
.
m.www.yahoo.
com/

6??

Scripts
:
3
1

Timeline^^^Rro*iks

197k

L,-. ------ -------1 _

UJ
;

r*(

::

ci*

Storage

4 Console

sm
6S7
e mm
i
-----J ----------- -------- ~

IZU

1
.
9
*
1

*isi

460*

4
0

liAi *
(D

*
i
u
.

|t

Elements

TIMELINES
0 Loading
Scripting
Rendering

. 10.10. Timeline
Chrome

Profiles ()
Chrome Java
Script (. 10.11).
,

238

10.

. ,
Compared to Snapshot ( )
Profiles (). +/ Count (+/- )
Size () .
Clements wjResourcs
,Scripts
Constructor
ico
de
)
{
c
l
o
s
u
r
e
}
] ""*1
jS
t
r
i
n
g
(anonvmous)
j | | j Profik2
Object
Array
Function
(
g
l
o
b
a
lp
r
operty)
HEAP SNAPSHOTS
HTMlDivPcment
Element

HTMUIement
RegExp
hrrl Snapshot 2
} UsedBMBof11MB(70 HTMLTabteCellEJement
MTMLOocument
!j Snapshot 3
i>%Ilhd6MBo
f1
CMBO
X)

Timeline

CPU PROFILES

|] p,#,,i* j

W Code

-L473MB

>Console OL
Pro
fi
le
*^^^Storage
Count s *Count Size
.....
8900 3.473MB_____0!
8971 1.248MB HHE2 K I T
20694 974.39..
08
0
42 207.75...
0B

.
0
0B
3086 20254.
1713 130.92
0
0B
1870 59.17KB
0
0B
7428 58.03KB
0
0B
1
1
4
8
K
B
0
0
8
478
0
0B
426 9.98KB
0
08
389 9.61KB
188 9 55KB
0
0B
344 8.06KB
0
0B
0B ,
12 6.48KB
0

Objects and Data


2.69SMB

Other
269.09KB

Compared to Snapshot 1 i

Ol L2

Puc. 10.11.
Chrome



.

. , ,
, ,
.

. , Safari 4, IE 8 , Firefox 3.5
Chrome, ,
, ,
.
,
.


, , ,
.
,

Page Speed

239

.

. ,
. ,
, ,
, , .

Page Speed
Page Speed - ,
Google
Firebug, , Net () Fi
rebug, , -. HTTP-
,
JavaScript-, ,
, .
, , ,
.
http://code.google.com/speed/page-speed/.
Profile Deferrable JavaScript (
JavaScript), Page Speed,
,
,
.
. . 10.12
,
load window.
,
, .

.
Page Speed Firebug Page Speed
Activity ( ).
Net () Firebug,
.
,
,
.
,
.
. 10.13, ,
, - .
,
.

240

10.

81

Console

Analyze Performance

HTML

CSS

Show Resources

Script

DOM

Net

Page Speed

Page Speed Activity

Help

Overall performance summary:


A
>

C om bine external JavaScript


T D efer loading o f JavaScript

98.4% o f the JavaScript loaded by this page had not been invoked by the tim e the onload
handler co m pleted. (Cached Result)
h ttp ://rn .w w w .y a h o o .c o m 3 9 functions uncalled o f 4 1 total functions. (Toggle Function
View)
h ttp ://L y im g .e o m /a /lib /a r c /a r c a d e _ 0 .l.9 8 .js 7 1 6 functions uncalled o f 73 3 total
functions. (Toggle Function View)
co m b o ? m etro /u ip lu g in s/a u to h id e _s ervic e_ 0.1 .5.js& m e ... 5 5 1 functions uncalled o f 55 2
total functions. (Toggle Function View)

Puc. 10.12. Page Speed,


| Record
URL

Console

Stop

jfd/23143322

HTML

CSS

Script

Show Uncalled Functions


t 0ms

DOM

h t*

Page Speed Activity

Page Speed

Show Delayable Functions

1200ms

/cust/msnbc/ucs.
j
s
N on~H TTP re s o u r c e s ;

F
ir
ef
oxJ
a
v
a
s
c
r
i
p
t

ConnectionWait DNS
Connect
Connected
Receive
Cachef
t
t MiDataA
vailable JSParse

Send
JSExecute

Puc. 10.13. Page Speed

,
,
. Page Speed Activity (
) , ,

(. 10.14).
,
, ,
.

,
.

241

Fiddler
^P a g e S)>eed Activity Delay,-*>le Functions
Delayable [ Init Time
312 ms
750 ms
312 ms
750 ms
312 ms
750 ms
312 ms
750 ms
419 m e

7 m e

| First Invocation | Name


[ Source
1062 ms
anonym..
fUxtion
1062 ms
anonym..
fixction
fUxtion
1062 ms
anonym..
1062 ms
anonym..
fUxtion
1 ? m e

a n n rw m

(d, a, c)
(c, d, b)
(a) {
0 {

fi r * - tio r ) ( a

K \ /

File
var e, i = 0, ... http://...
= = = wi... http://...
return !!a &&
... http://...
var b = arguments... http://...

{
{

r o b im

o a r lV

h H rv / /

Page Speed Activity - Uncalled Fundticxis


Init Time
750 ms
750 ms
750 ms
750 ms
750 ms
750 ms
750 ms
750 ms
750 ms

I Source
TFiie
Tb I
1 Name
function evalScript(i, a ) {
if (a.src) {
D.ajax({urI... http ://w ...
evalScript
num
function num(a, b) {
re tu n a[0] && parseInt(D.curCSS... http://w...
anonymous
function 0 {
if (D.isReady) {
return;
>
... http://w...
anonymous
function 0 (
if (D.isReady) {
return;
>
... http://w...
anonymous
function 0 {
if (D.isReady) {
return;
>
... http://w...
bindReady
function bindReadyO {
if( M
return;
>
... http://w...
anonymous
function 0 {
retLm this.length;
>http://w...

function (a) {
retLm a = = undefined ? D.makeArray(thi... http://w...
anonymous
anonymous
function ( b ) {
var a = D(b);
a.prevObject = this; ... http://w...

Puc. 10.14.

Fiddler
Fiddler - ,
HTTP-, ,
,
. Windows,
(Eric Lawrence),
-.

http://www.fiddler2.com/fiddler2/.
Fiddler
IE Firefox. Internet Explorer
, Firefox -
Tools (). Fiddler
.
, -. WinlNET Fiddler,
. (
Opera Safari) WinlNET,
Fiddler ,
. Fiddler
, -, -
Fiddler (127.0.0.1, : 8888 ).
Firebug, Page Speed -,
Fiddler , , -

242

10.


(. 10.15).
f Fiddler - HTTP Debugging Proxy
File Edit Rules Tools View Help
^Comment
Reissue X Remove - Resume AH ; Streaming jjpAutpQecode |^ F in d IS Save | Laurri
Web Sessions
jT T p t "d
S Inspectors | / AUtoResponder |
Request Builder | Piters ~ Timeline |
1 Result I Protocol j |]
#
HTTp Hi
so:'
http
]|

1
200 HTTP

2
200
3
304 HTTP
/combo
4
200 HTTP
/arcade_0.13.cis
5
200 HTTP
/
6
200 HTTP
korrho
7
200 HTTP
/food_psticides-pd5m
8
200 HTTP
/vickd-pd.jpg
9
200 HTTP
10
200 HTTP
/?0i50mfs*f
11
200 HTTP
/>*_22_111908>
12
200 HTTP
/spHt#_ma^bad_riat_srchbtl_0
13
200 HTTP
*
I
14
200 HTTP
/onbo
15
200 HTTP

>]16
304 HTTP

Til

StatisfacsI

Puc. 10.15. , Fiddler


,
.
Timeline ( ),
.
,
,
.
Statistics ()

, DNS
TCP/IP,
(. 10.16).

. , DNS
TCP/IP
.


( ).

243

YSlow

_
Web Session*
j ResUt | Protocol |
Host HTTP m.w w.yahoocom
HTTP m* m yahoocom
wyahoocom
w.yahoocom
l.yimg.com
l.ymg.com
l.ymgcom
t
.
yimg.com
d.ymg.com
dyinQ.com
dyng.com
l.ymgcom
I
.
yrag.com
I
.
ymg.com
d.yrr
tg
.c
om
d
.y
rr
tg
.c
om
d.vimg.com
l
.
y
i
m
gcom
I
.
ylng.com
I
.
ymg.com
l
.
y
i
m
gcom
I
.
ymg.com
d.ymg.com
l.yimg,com
d.ymg.com
d,ymg.com
d.ymgcom
d.ymg.com
d.ymgcom
d.ymg.com
d
.yimg.com
d.ymg.com
d.ymg.com
d.ymgcom
l.ymgcom

|
or*
$Request 8uicfer
(2) Stabeebcs
j
inspectors
Request Count: 54
33.323
Bytes sent:
Bytes Received: 335,189
ACTUAL PERFORMANCE
Requests started at:
17:4S:26:1573
Responses completed at:
8292
Aggregate Session time: 00:00:12:9687
Sequence (1 time: 00:00:45.718750
DNS Lookup time:
1,408ms
TCP/IP Connect time: Sims
RESPONSE COOES
http/30
2:
3
http/
200:
SI
PESrCNSE 5 (byContent-Type)
text/ison: 1,549
applicationA~shocKv>ave-flash: 33,589
applicatton/*oavascript: 120,281
text/css: 39,812
-headers: 18,616
inuge/jpeg: 22,662
image/pno: 14,383
text/htmf: 37,603
image/gif: 4 6 ,6 94

fmelft
/ AutoRejponder

| j CapyJI&Sito

Puc. 10.16. Statistics Fiddler

Fiddler Windows.
- Charles
Proxy, Windows, Mac OS.

http://www.charlesproxy.com/.

YSlow
YSlow

. (Ste
ve Souders) Yahoo!
Firefox ( GreaseMonkey).
Firebug,

244

10.

Yahoo!.
http://developer.yahoo.com/yslow/.
YSlow ,

. , ,
,
.
, ,

.
. 10.17 , YSlow
-.

.
.
? a
ALL (22)
F

Make

Console
FILTER BY:
fewer

HTML

CSS

DOM

Net

YSlow -r

CONTENT (6) | COOKIE j CSS <6>'| IMAGES (2) [JAVASCRIPT (4)

HTTP requests

F Uk a Content Delivery Network (CON)

Script

Atld Expires

Compress components

Pm CSS at top

Grade F on Make fewer HTTP requ<


Thx> p a g r Has
* p>ye has

hewers

with

Put JavaScript at bottom

Avoid CSS expressions

21 e x te rn a l ja v a sc rip t %
25 e x te rn a l batM jroim c

gzip
Decreasing the number of component
page, resulting m faster page loads. S<
combine multiple scripts into one sen
and Image maps.
Read More

Puc. 10.17. YSlow:

,
. . 10.18 ,
JAVASCRIPT,
.
, ,
, . ,
, ,
,
.

245

dynaTrace Ajax Edition

-If
Grade

Console

CSS

Script

Components | Statistics | Tools

Grade
ALL (22)

HTML

Overall performance store fcS

flLlLH BY:

DOM

Nci

YSlow j

Rule vets ( YSIow(V2)


Rulcvet applied: YSk*vfV2)

URL: >tttp;//www.n

CONTLNT (0) | COOKIL (2) | CSS {) | IMAGES (2) | lAVASCRJTT C4) | S

Pul JavaScript at bottom

N/AM ake JavaScript and CSS external

Minify JavaScript and CSS


A Remove duplicate JavaScript and CSS

Crade on Minify JavaScript and CSS

Puc. 10.18. YSlow: no JavaScript-

dynaTrace Ajax Edition


dynaTrace,
Java/.NET, Ajax Editi
on,
Internet Explorer (
Firefox).
-

.
, .
.
dynaTrace http://ajax.dynatrace.com/pages/.
Summary, . 10.19,
, ,
.

.
Network (), . 10.20,

, DNS,
. , ,
, .
()
().
JavaScript Triggers ( JavaScript)
, (. 10 .21).

246

10.

(load, click, mouseover ),


.

File View Help

-M*l

11..

\* dvnaTrace AJAX Edition

J*

| J *

) ' Welcome f Summary


| Start Time [s]
URL
http://yahoo.com/

I Network [ms] | JavaScrpt [ms] I Rendering [ms] | Page Load Time [ms] |

Resources

Numbero
fresourcesloadedv
i
anetworka frombrowsercache

s is ?s :<o :<s

Network

Timespentonnetworka
c
t
i
v
i
t
i
e
s
.P
a
r
a
l
l
e
la
c
t
i
v
i
t
i
e
sareaccumulated.

1*4174 m}~

0<hr

M m

DftS

lm 9 1FI**

JavaScript Triggers

Time*pcrtonJ
a
v
a
S
c
r
i
p
te
xe
c
u
t
i
o
n
,t
r
i
g
g
e
i
e
dbyshowne
v
c
r
t
t
s
.

{738S ms|

Connct 5crv*r Tirfti

JavaScript APIs

TimespentonJ
a
v
a
S
c
r
i
p
texecutionfromshownA
P
I
s
.

10m|
1

JCLL
503 mtf -

1080 im |
<html>

Load Evrmj

Page
CPU
JavaScript
Rendenng
Network
Event

< yot_0.2 1 cor_1.0.16

cenHnU4rautibkdthvM lw0 .1 J

http://yahoo.com/

Lrli

___

L ii J

__ ___

tiiDHi 11 ib
ID |D

QUID

DO

Puc. 10.19. dynaTrace Ajax Edition: Summary

(Ajax)
, ,
,
. ,
,
- Ajax.

247

dynaTrace Ajax Edition

Fie

View

j*-'t lesiajKE*!^
5 Welcome Summary

fb te tw o rV

|<teton>

hflpV/l yimg.c
htlp://l.yimg.c...
Iit1p.//I.ylmg c ...
htip://*dmedi...
;/ * bc.y...

no
no
no
no
no

200... text..
200... text..
200... appl..
200... imu
200... ...

Net
Net
Not
Nt
Net

447U
61701
153...
95
0

065
0.54

007
0.00
0.00

036
0.6

016
005

006
007

<M |unt Ixvadur:

Accept

<*Oite

C n u x fttg (tfip,
L ' rr: hnp7/rri.www.yjroo.com/
ftccnpt-bmqudgn:
MccilU/4 0 (ccimpdrtirte; MSIE 7 0; WwJow* NT 5. 1; Tidw n /4 0; .NET ClR
.0.50727; y * 0)
iyiuiTroco:
A){86EeE5EF-5CBCMC78-BOAI>17F50CW:0333l}.PC-! 1;4;17. E A^ent

id :
bconllnk: to,
tnstruMittncioit: b,
nuduleapx: b,
vieweventa ["click"),
l n i t t fn m - tie n le l

X ite S tr. 29 Nov 2009 15: 19:16 GMT


:jche-Control: ma*-age 315360000
ixplre* Wed, 27 Nov 2019 15: 19:18 GMT
Content-Type: application/* )avascrt
*g e : 44716
Connection: keep-alne
er: YTS/1. 17.22

thi*.Y c.gecScrvlcc("yui"):
thl*.be*coi link - c.oecStclngCBCi'CW LINK");
t h u Id - e g e t ld ( ) :
th ia .M o d u lc a p l c :

.J

56 row* ftxrd (1 row elected)

Puc. 10.20. dynaTrace Ajax Edition: Network

I* * d v n a T ra c e E d itio n
File View Help

.J n jx J

cX

*
4f r * Sitowing: JavaScript (filtered) I Network (filleted) | Rendering (IMtered) | Culom table filler ( a l)

| Time Chart | Start Tim... |purat).. '


5.97
1224.44
1077 70
26.59
[
25.09
743.53
3.37
703.18
692.61
4.66
14.21
367.09
15.51
258 71

JS [ms] j CPU Time... |


109.37
148.00
80.61
78.12
291.57
218.75
121.36
78.12
142.16
125.00
61.98
46.87
43.91
15.62

Size [
1885
1533
8428
2842
3276
2037
1468

| Activity kmd 1Details


JavaScript mouseout event on <li>
JavaScript mouseout event on <a dass="y-fp*-AJAX
mouseover event on <ll ^-"-_2.
AJAX
mouseover event on <a class-1
"y-lp.
AJAX
mouseover event on <a 1="-.
AJAX
mouseover event on omg class=" I.
AJAX
mouseover event on <$pan class=*t.

1.1.......................

Activity
J &L[<tf]
d CHiideModute
id <arwnymous>
iy atTimeout
.d ** JavaScript FKBCUtrm
jd t 'I Asynchronous Lrik fbetTirneout)

I API
I
core_1.0.16
contentca...
yui_0.2.1
DOM
JavaSo pt
-

tJ <anonyrnous>

Start I
5.83
5.84
5.09
5.93
6.06
6 06

yui_0.2.1

5.09

jJ e.test
yui 0.2.1
5.90
l i ...........- .................................................................................................................................................1
|
Total [rtj^J
Contributor
| Invocations I Ext *] Stack Element
<*>ad_embedObj
- Rendering (Calculating gene...
collapse
__
< closeCurrentModule
<*>removeClass
^Renderng (Scheduling layou...
C*>tokence
| <*> filterNodes
,
i L ..................................... ...... J
Contributors API dlstrbutton |

1
5
1
1
2
583
13
10

JU
JJ

|^,lAsynchronous Lri, (...


*** JavaSa pt Execution
0-setTlmeout
<anonymous>
CShideModute
L[az]
CDonBodyMouseout
OL[az]
notify
n

r : .......................... i

Duration [me] 1
1218.61
1218.60
1218.55
1218.50
1?1.
1218.38
0.02
0.01

JSfrmll Toi*P
142.12
142.10
142.03
141.98
|
i4i.es
141.59
-J
0.02
0.01

JiJ

h .a p p ly ( g ,
return;

0.
0.
o.
0.__
0.
0.
0.
0. i
i r

!
1 );

>'
e (J) ? set In te rv a l(k , n) :
return (
id : e,
in t e r v a l: j ,
can cel: function!)
4 ...........1 .........................i

31 rows found (1 row selected)

Puc. 10.21. dynaTrace Ajax Edition: PurePaths

j1

248

10.


-
,

, .

;
, ,
.
,
HTTP-,


.

.
,
,
.

,
, ,
.
, ,
,
.
,
.

+ (), , 110
+= (-), , 110

eval(), , 46, 176,191


execute(), , 47
Expires, , 186
ExpiresDefault, , -
Apache, 213

add(), , 39
addEventListener(), , 195
Ajax (Asynchronous JavaScript and XML,
JavaScript XML), 160
, 160
, 171
Apache, -
ExpiresDefault, 213
Apache Ant, , 204
array.join(), , 110
assignEvents(), , 48

BOM (Browser Object Model -


), 50

F
factorial), , 103,106
Fiddler,
, 241
Firebug, , 226
Firefox,

, 142
, 112
forEach(), , 94
for, , 88
for-in, , 89
Function(), , 191

childNodes, , 71
Chrome,
, 237

, 142
JavaScript,

GET- POST-
XHR, 162
gzip-, 210, 212

202

Closure Compiler,
JavaScript-, 211
Closure Inspector, Firebug,
211

concat(), , 115
console.time(), , 228
cssText, , 78
CSS-, , 72
CSS-, , 34

D
Date, , 220
displayName, , 234
do-while, , 88
dynaTrace,
, 245

hasOwnProperty(), , 51
rhover, , IE, 82
HTML,
, 179
HTML-
, 66
, 69
HTTP-, Ajax, 186

I
IE (Internet Explorer),
nextSibling, , 71
,
144
script, 29
, 230
XHR, 188
, 113

250
if-else,
, 97
switch, 95
initUI(), , 44
innerHTML,
DOM, 61
JavaScript-
, 213
, 209
, 205
, 206
jQuery,
gzip-, 212
JSMin,
JavaScript-, 209
JSON (JavaScript Object Notation
JavaScript), 175
JSON-P (JSON with padding - JSON
), 178

L
$LAB.script(), , 35
$LAB.wait(), , 35
LABjs, , , 35
LazyLoad, ,
, 34
length, , 66
loadScript(), , 30

mergeSort(), , 104
message, , 156
multistepO, , 152

onmessage, , 156
Opera,

, 143

Page Speed,
, 239
postMessage(), , 156
POST- GET-
XHR, 162
processArray(), , 150
profileEnd(), , 228

Q
querySelector(), , 201
querySelectorAll(), , 73, 201

R
readyState,

, 166
XHR, 162
removeEventListener(), , 195

Safari,
, 238

, 233

, 142
, 157
[[Scope]], , 48
<script>, , , 163
<script>,
defer, , 26
, 22
setlnterval(), , 145,191
setTimeout(), , 145, 191
smasher, , 216
string.concat(), , 110
switch,
if-else, 95

this, , 56
toStringO, , 51
trim(), , 132
try-catch, , 45, 102

V, W
var, , 88
while, , 88
with, , 44

X
XHR (XMLHttpRequest), , 161
GET- POST-, 162
IE, 188
, 164
, 168
XML, , 171
XPath,
XML-, 174

Y
YSlow,
, 243
YUI 3, , , 33
YUI Compressor,
JavaScript-, 209
YUI Profiler, , 221

251

, 87
,101
, 95, 97
, 87
, 225
YUI Profiler, , 225
, , 123

Ajax, 188
LABjs, 35
LazyLoad, 34
YUI 3, 33
, 199
, 197

, 238
, 21

, 238
, 139
WebKit
innerHTML, 64
, 141
,
101

XPath, 174

, 139
, 21, 37
DOM, 58
DOM JavaScript, 58

eval(), 192
, 137

,
, 41
DOM, 79
, 24

, 83
,150

DOM, 75
, 75
, 46
<script>, 163
script, 27
, 37
, 38
, 50

Expires, 186
HTTP-, 186
, 157
CSS-, 34
, 157
, 32, 238
, , 47
, Ajax, 161
, HTML-, 67
,
, 55


, 119
, 128
- (Safari), 233
, 125
, 125
, 54
, , 157
, 118
, 121
, XML, 174
, 200
, 129

, 162

, 127
, 123

try-catch, 45, 102


var, 88
with, 44
, 219
dynaTrace, 245
Fiddler, 241
Firebug, 226
Page Speed, 239
YSlow, 243
YUI Profiler, , 221
- Safari, 233
,
225
JavaScript-,

JavaScript-,
216

Chrome, 237
IE (Internet Explorer),
230

220

252

XMLHttpRequest, 31
, 121
, 145

, 104
, 94

, 125
, 130

childNodes, 71
HTML-, 66
, 69
, 110
, 200
, 40
, 65

JavaScript-, 213

Ajax,185
, 55
, 81

, , 37

HTML-, 69
, 41, 60


HTMLCollection, 66
for-in, 89
,
, 200
, , 105
, 22
, 50, 200
$LAB.script(), 35
$LAB.wait(), 35
array.join(), 110
concat(), 115
forEach(), 94
hasOwnProperty(), 51
postMessage(), 156
querySelector(), 201
querySelectorAll(), 73, 201
string.concat(), 110
toStringO, 51
trim(), 132
, 200

, 110
, 201
this , 56
JavaScript-, 209

DOM, 71
, 26
script, 27

XMLHttpRequest, 31
, 26
, 32
, 129

, 39
, 46
, 47
,
148
,
, 123
JavaScript-, 205
, 40

Date, 220
HTMLCollection, 66
, 40
, 193

, 142
, 101
, 197
,
, 123
, 195
, 26
, Ajax, 168

Net, Firebug, 229


Profiles (Safari), 233
Resources (Safari), 236
,
Firebug, 227
, 160
, 161
, 168
, 75

, 76

, 81
, 78

253

, 41
, , 41
, 37
,
, 78
, 120
, 191
, 194
, 99
, 139
,
139
, 145

, 139
, 155

,
139

, 139
JavaScript, 206
, 196
, 191
, 197
, 200
, 193
, 195
, 191
, 194
,
196
,
Firebug, 228

CSS-, 72
DOM, 58

, 76

Ajax, 185
JavaScript , 21
, 37
, 54
, 47
JavaScript, 47
, 44

HTML, 181
JSON, 177
JSON-P, 178
XML, 174
DOM, 58, 59
, 41
trim(), 137

, 116,127

eval(), 192
, 154
, 89
, ,
55
, 50
JavaScript-, 220
JavaScript-, 216
DOM, 58
HTML-, 66
innerHTML, , 61
, 58
, 83
, 71
, 65
, 75
JavaScript-pecypcoB, 215
,
, 39
, 116
, 123
, 118,121
, 117
, 131
, 120
, 116, 127
, 132, 137
, 101
, 104
, 105
,
101

, 103

, 211
, Firefox, 112
, 50
cssText, 78
displayName, 234
innerHTML, 61
length, 66
, 50
, 55
, CSS, 72

(Content Delivery Network, CDN), 215
, 210, 211
, , 169
, 113

254

message, 156
onmessage, , 156
,
XHR, 164
, , 101
,
, 78

, 110
, 132
, 21
, 238
, 22
, 226

, 99

, 154
, 145
, 148

, , 50

, , 55

XML, 171
, 181
, 184
,
DOM, 80
,150
add(), 39
addEventListener(), 195
assignEvents(), 48
console.time(), 228
eval(), 46,176,191
execute(), 47
factorial), 103,106
initUI(), 44
loadScript(), 30
mergeSort(), 104
multistep(), 152
processArray(), 150
profileEnd(), 228
removeEventListener(), 195
setlnterval(), 145,191
setTimeout()* 145,191
, 225

, 55
, 40

, , 65
- DOM, 72
, 87
,101
, 95, 97
, 87
, 132,137
, 95, 97
if-else, 95
switch, 95
, 99


, 39
, 44
, 44
, , 52
, 87
, 94
, 89
, 88

console.time(), 228

, 157
, 157
JavaScript-, 213
JavaScript-, 209
JavaScript-, 205
JavaScript, 206
, 155
, 156
, 157
, 155
, 157
, 171
HTML, 179
JSON, 175

, 50
, 54
, 50

, 55
, 37
, 50
, 52

, 69
, , 37

OREILLY
JavaScript.
-,
JavaScript -
. , Java
Script . ,
,
. , , ,
DOM, .
, Yahoo!,
-,
JavaScript - , , ,
-
,
JavaScript.
,
.
:

.
,
JavaScript.
JavaScript,
DOM.
.

.
.

HTTP- .
- JavaScript,
-.


. ,
JavaScript.
,
, Yahoo! Search
: J r w S cRIPT/ -

(812) 380-5007, (495) 638-5305


ISBN978-5-93286-213-1

9 785932

862131

www.symbol.ru