Professional JavaScript for Web Developers - Matt Frisbie - E-Book

Professional JavaScript for Web Developers E-Book

Matt Frisbie

3,8
46,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Update and upgrade your JavaScript skillset for ES 2023 with the ultimate JavaScript guide for pros Professional JavaScript for Web Developers, 5th edition, is the gold-standard in intermediate-to-advanced JavaScript programming development books. The author dives directly into the inner workings of JavaScript to help you clean up your code and become a more sophisticated and talented JavaScript developer. From object-oriented programming and inheritance to combining JavaScript with HTML and other markup languages, expert computer engineer Matt Frisbie walks you through everything you need to know to level-up your JavaScript game. This new edition is updated to include ECMAScript 2023 and later standard releases, the most useful techniques, and a relentless focus on code that works seamlessly in mobile web browsers and with the latest common frameworks and libraries. With this book, you will: * Get up to date with ECMAScript 2023 * Get acquainted with the newest frameworks and libraries * Explore advanced topics such as web animation, workers, and the latest APIs * Get a head start on future ES releases * Learn to use modern syntax and best practices * Understand how to optimize performance in JavaScript applications * Master asynchronous programming patterns using promises, generators, and async/await Perfect for those who think they already know JavaScript "pretty well," Professional JavaScript for Web Developers, 5th edition, is the pro-level update that intermediate and advanced web developers have been waiting for.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 1654

Veröffentlichungsjahr: 2023

Bewertungen
3,8 (18 Bewertungen)
5
8
2
3
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

COVER

TABLE OF CONTENTS

TITLE PAGE

FOREWORD

INTRODUCTION

WHO THIS BOOK IS FOR

WHAT THIS BOOK COVERS

HOW THIS BOOK IS STRUCTURED

WHAT YOU NEED TO USE THIS BOOK

1 What Is JavaScript?

A SHORT HISTORY

JAVASCRIPT IMPLEMENTATIONS

SUMMARY

2 JavaScript in HTML

THE

<SCRIPT>

ELEMENT

INLINE CODE VERSUS EXTERNAL FILES

DOCUMENT MODES

THE

<NOSCRIPT>

ELEMENT

SUMMARY

3 Language Basics

SYNTAX

KEYWORDS AND RESERVED WORDS

VARIABLES

DATA TYPES

OPERATORS

STATEMENTS

FUNCTIONS

SUMMARY

4 Variables, Scope, and Memory

PRIMITIVE AND REFERENCE VALUES

EXECUTION CONTEXT AND SCOPE

GARBAGE COLLECTION

SUMMARY

5 Basic Reference Types

THE DATE TYPE

THE REGEXP TYPE

PRIMITIVE WRAPPER TYPES

SINGLETON BUILT-IN OBJECTS

SUMMARY

6 Advanced Reference Types

THE OBJECT TYPE

THE ARRAY TYPE

TYPED ARRAYS

THE MAP TYPE

THE SET TYPE

WEAK REFERENCES

THE WEAKMAP TYPE

THE WEAKSET TYPE

ITERATION AND SPREAD OPERATORS

SUMMARY

7 Iterators and Generators

INTRODUCTION TO ITERATION

THE ITERATOR PATTERN

GENERATORS

ASYNCHRONOUS ITERATION

SUMMARY

8 Objects, Classes, and Object-Oriented Programming

UNDERSTANDING OBJECTS

OBJECT CREATION

CLASSES

SUMMARY

9 Proxies and Reflect

PROXY FUNDAMENTALS

PROXY TRAPS AND REFLECT METHODS

PROXY PATTERNS

SUMMARY

10 Functions

ARROW FUNCTIONS

FUNCTION NAMES

UNDERSTANDING ARGUMENTS

NO OVERLOADING

DEFAULT PARAMETER VALUES

SPREAD ARGUMENTS AND REST PARAMETERS

FUNCTION DECLARATIONS VERSUS FUNCTION EXPRESSIONS

FUNCTIONS AS VALUES

FUNCTION INTERNALS

FUNCTION PROPERTIES AND METHODS

RECURSION

TAIL CALL OPTIMIZATION

CLOSURES

IMMEDIATELY INVOKED FUNCTION EXPRESSIONS

SUMMARY

11 Promises and Async/Await

INTRODUCTION TO ASYNCHRONOUS PROGRAMMING

PROMISES

ASYNC FUNCTIONS

SUMMARY

12 The Browser Object Model

THE WINDOW OBJECT

THE LOCATION OBJECT

THE NAVIGATOR OBJECT

THE SCREEN OBJECT

THE HISTORY OBJECT

SUMMARY

13 The Document Object Model

HIERARCHY OF NODES

WORKING WITH THE DOM

SELECTORS API

ELEMENT TRAVERSAL

HTML5

SUMMARY

14 DOM Extensions

STYLES

TRAVERSALS

RANGES

OBSERVER APIS

OBSERVER PERFORMANCE

SUMMARY

15 Events

EVENT FLOW

EVENT HANDLERS

THE EVENT OBJECT

EVENT TYPES

MEMORY AND PERFORMANCE

SIMULATING EVENTS

SUMMARY

16 Animation and Graphics with Canvas

USING REQUESTANIMATIONFRAME

BASIC CANVAS USAGE

THE 2D CONTEXT

WEBGL

SUMMARY

17 Scripting Forms

FORM BASICS

SCRIPTING TEXT BOXES

SCRIPTING SELECT BOXES

RICH TEXT EDITING

SUMMARY

18 JavaScript APIs

ATOMICS AND SharedArraybuffer

CLIPBOARD API

CROSS-CONTEXT MESSAGING

ENCODING API

BLOB AND FILE APIs

FULLSCREEN API

GEOLOCATION API

DEVICE APIs

MEDIA ELEMENTS

NOTIFICATIONS API

PAGE VISIBILITY API

STREAMS API

URL APIs

TIMING APIs

WEB COMPONENTS

THE WEB CRYPTOGRAPHY API

SUMMARY

19 Error Handling and Debugging

BROWSER ERROR REPORTING

ERROR HANDLING

ERROR HANDLING STRATEGIES

DEBUGGING TECHNIQUES

SUMMARY

20 JSON

SYNTAX

PARSING AND SERIALIZATION

SUMMARY

21 Network Requests and Remote Resources

THE FETCH API

CROSS-ORIGIN RESOURCE SHARING

THE BEACON API

WEB SOCKETS

THE EVENTSOURCE API

SUMMARY

22 Client-Side Storage

COOKIES

WEB STORAGE

INDEXEDDB

SUMMARY

23 Modules

UNDERSTANDING THE MODULE PATTERN

WORKING WITH PRE-ES6 MODULE LOADERS

WORKING WITH ECMASCRIPT MODULES

SUMMARY

24 Workers

INTRODUCTION TO WORKERS

DEDICATED WORKERS

SHARED WORKERS

SERVICE WORKERS

SUMMARY

25 Best Practices

MAINTAINABILITY

PERFORMANCE

STRONG TYPING

DEPLOYMENT

SUMMARY

A ES.Next

ARRAY FIND FROM LAST METHODS

HASHBANG/SHEBANG GRAMMAR

SYMBOLS AS WEAKMAP KEYS

CHANGE ARRAY BY COPY

B Strict Mode

OPTING -IN

CLASSES AND MODULES

VARIABLES

OBJECTS

FUNCTIONS

Using

eval()

eval

AND ARGUMENTS

COERCION OF THIS

OTHER CHANGES

C JavaScript Libraries and Frameworks

FRAMEWORKS

USEFUL LIBRARIES

D JavaScript Tools

PACKAGE MANAGERS

MODULE LOADERS

MODULE BUNDLERS

COMPILATION/TRANSPILATION TOOLS AND STATIC TYPE SYSTEMS

HIGH-PERFORMANCE SCRIPT TOOLS

EDITORS

BUILD TOOLS, AUTOMATION SYSTEMS, AND TASK RUNNERS

LINTERS AND FORMATTERS

MINIFIERS

UNIT TESTING

DOCUMENTATION GENERATORS

INDEX

COPYRIGHT

DEDICATION

ABOUT THE AUTHOR

ABOUT THE TECHNICAL EDITOR

ACKNOWLEDGMENTS

END USER LICENSE AGREEMENT

List of Illustrations

Chapter 1

FIGURE 1.1: Components of JavaScript

FIGURE 1.2: Example DOM node hierarchy

Chapter 3

FIGURE 3.1: Breakdown of binary integer representation

FIGURE 3.2: Before and after left shift operation

FIGURE 3.3: Before and after right shift operation

Chapter 4

FIGURE 4.1: Variable object before and after copy

FIGURE 4.2: Relationship between variable objects and the heap

FIGURE 4.3: Example scope chain for nested functions

Chapter 8

FIGURE 8.1: Diagram showing the relationship between

constructor

,

prototype

,...

FIGURE 8.2: Diagram showing the effects of assignment and

delete

operations...

FIGURE 8.3: Diagram demonstrating effects of prototype assignment

FIGURE 8.4: Diagram demonstrating the relationship between instances, constr...

FIGURE 8.5: Diagram demonstrating the path of a prototype chain

Chapter 10

FIGURE 10.1: An execution context's scope chain

FIGURE 10.2: Closure scope chain

Chapter 12

FIGURE 12.1: The

alert()

dialog

FIGURE 12.2: The

confirm()

dialog

FIGURE 12.3: The

prompt()

dialog

Chapter 13

FIGURE 13.1: An HTML document hierarchy

FIGURE 13.2: A diagram of the parent, child, and sibling relationships

Chapter 14

FIGURE 14.1: Illustration of various offset dimensions

FIGURE 14.2: Illustration of various client dimensions

FIGURE 14.3: Illustration of various scroll dimensions

FIGURE 14.4: Visual representation of DOM tree

FIGURE 14.5: Illustrated order of depth-first traversal

FIGURE 14.6: Illustration of two different ranges

FIGURE 14.7: Illustration of range character selection

FIGURE 14.8: Comparing a DOM tree and a range document fragment

FIGURE 14.9: Illustration of range collapse

FIGURE 14.10: Illustration of the effect of

setEndBefore()

Chapter 15

FIGURE 15.1: Illustration of event bubbling

FIGURE 15.2: Illustration of event capturing

FIGURE 15.3: Illustration of client coordinates in a viewport

FIGURE 15.4: Illustration of screen coordinates in a browser

FIGURE 15.5: Illustration of mousewheel events

FIGURE 15.6: Example of a confirm dialog

FIGURE 15.7: Illustration of orientation change events

FIGURE 15.8: Illustration of device axes

FIGURE 15.9: Illustration of alpha, beta, and gamma with respect to device o...

Chapter 16

FIGURE 16.1: Overlapping semi-transparent rectangles drawn with

fillRect()

FIGURE 16.2: Overlapping rectangle outlines drawn with

strokeRect()

FIGURE 16.3: Removing content with

clearRect()

FIGURE 16.4: Drawing with

arc()

paths

FIGURE 16.5: Writing text with

fillText()

FIGURE 16.6: Demonstration of varying text alignment

FIGURE 16.7: Demonstration of varying font size and width

FIGURE 16.8: Transforming canvas content with

rotate()

FIGURE 16.9: Drawing images with

drawImage()

FIGURE 16.10: Demonstration of canvas shadows

FIGURE 16.11: A linear canvas gradient drawn with

createLinearGradient()

FIGURE 16.12: A radial canvas gradient drawn with

createRadialGradient()

FIGURE 16.13: Repeating images drawn with

createPattern()

FIGURE 16.14: Diagram of coordinates defining a viewport

FIGURE 16.15: Diagram of coordinates within a viewport

FIGURE 16.16: Drawing with

drawArrays()

and

gl.TRIANGLES

FIGURE 16.17: Result of passing other arguments to

drawArrays()

Chapter 19

FIGURE 19.1: Grouped console log messages

FIGURE 19.2: Nested groups with collapsed subgroup

FIGURE 19.3: Nested group with expanded subgroup

FIGURE 19.4: Output of

console.table()

FIGURE 19.5: Output of

console.trace()

Chapter 23

FIGURE 23.1: An example dependency graph

FIGURE 23.2: Depth-first module load with Module A entrypoint

FIGURE 23.3: Depth-first module load with Module C entrypoint

Guide

Cover

Title Page

Copyright

Dedication

About the Author

Acknowledgments

Foreword

Introduction

Table of Contents

Begin Reading

A ES.Next

B Strict Mode

C JavaScript Libraries and Frameworks

D JavaScript Tools

Index

End User License Agreement

Pages

v

xliii

xlv

xlvi

xlvii

xlviii

xlix

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

987

988

989

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

vi

vii

ix

xi

1053

PROFESSIONALJavaScript® for Web Developers

 

Fifth Edition

 

 

Matt Frisbie

 

 

 

 

 

 

FOREWORD

During nearly a decade at Amazon, I worked on a wide variety of projects including a petabyte-scale customer analytics cluster, an airport for drones, computer vision labeling tools, an open-source smart home specification, and even fitness watch firmware. None of these projects were inherently rooted in client-side web dynamism, but each of them had some facet that eventually involved JavaScript, either by necessity or by virtue of it being the best tool for the job.

Fifteen or even 10 years ago, a generalist software engineer with a career analogous to mine might have never had reason to learn JavaScript at more than a surface level, but today JavaScript has established itself as the lingua franca of the programming world. In 2022, JavaScript remained GitHub's most used language for the ninth year in a row, not even including Typescript contributions, which independently came in fourth.

React Native is exposing many career mobile developers to JavaScript, and Electron is doing the same for desktop applications. My work at Roboto exposes me to a number of robotics companies, and I can say with high confidence that there are even people out there building robots in Node. And of course, in the web development world, JavaScript is king.

JavaScript is not going anywhere, and as such it's a great investment for any software professional to become an expert practitioner and develop a deep understanding and intuition around the language. I've known Matt for close to two decades, and in that time, I haven't met another engineer who could better fill a 1,000-page technical document with poignant wisdom without wasting a word.

When I first met Matt, he didn't have his current wealth of early career accolades, such as being the first engineer at DoorDash, publishing multiple successful technical books, founding his own ventures, or working on extremely high-scale, public-facing projects at Google—back then he was just a nerdy teenager who could hit the high register on trumpet and was great at math.

Obviously a lot has changed in the time since, but two things that haven't are Matt's inherent curiosity and his ability to explain anything he truly understands to anyone who will listen. He's the kind of engineer who will lose sleep at night over not understanding the minutia about how something incredibly specific works, which is exactly the kind of person you want writing a technical reference. At the same time, his wealth of hands-on experience as an engineer, engineering leader, and entrepreneur gives him an excellent sense of what points need to be played up and what minutia can live in the margins.

This book is packed with pragmatic examples and tidbits of knowledge that will make you a better JavaScript developer whether you read for 20 minutes or 20 hours. I've gleaned some useful tips from every edition that I've read, and I'm excited for what you'll learn approaching this with fresh eyes!

—JOHN HUBBERTS

Founding Principal Engineer at Roboto

INTRODUCTION

A tech lead at Google once shared with me a compelling perspective on JavaScript: It's not really a programming language. The ECMA-262 specification defines JavaScript, but there is no single true implementation of it. Web browsers and their JavaScript engines all implement this specification as they see fit. Chrome has Blink/V8, Firefox has Gecko/SpiderMonkey, and Safari has WebKit/JavaScriptCore. What's more, the language swims in an ocean of supplementary specifications that govern APIs for everything that JavaScript touches: the DOM, network requests, system hardware, storage, events, files, cryptography, and hundreds of others. Therefore, JavaScript is more accurately characterized as a constellation of ECMAScript implementations buttressed by an API buffet.

The first edition of this book was published in 2005. Microsoft was still pushing its rogue JScript, Internet Explorer had over a 90 percent browser market share, mobile browsers were in the Stone Age, and jQuery wouldn't be released for another year. At the time this fifth edition was written in 2023, major browsers have coalesced around the ECMA-262 specification, over 70 percent of Internet traffic uses a Chromium-based browser, mobile browser traffic exceeds desktop traffic, and modern web development largely comprises manipulating frameworks like React and Angular.

Most web developers would identify the release of ECMAScript 6 as JavaScript's Cambrian explosion. Pre-ES6, the language advanced in infrequent and irregular lurches. A dire lack of critical language constructs led to ugly patterns, hacks, and fragmented workarounds. Post-ES6, the language enjoys more sophisticated and useful syntactical tools. Annual ECMAScript editions ensure the language addresses developer needs and stays abreast of industry trends. Modern JavaScript is beginner-friendly, is applicable in almost any domain, has an enormous development community, and enjoys a rich library of developer tools. As a result, developers flock to the language in droves: the Stack Overflow 2022 Developer Survey listed JavaScript as the most popular programming language for the 10th consecutive year.

In this book, JavaScript is covered from its very beginning in the earliest Netscape browsers to the present-day incarnations flush with support for a dizzying spectrum of browser technologies. The book covers many advanced topics in meticulous detail, yet it ensures the reader understands how to use these topics and where they are appropriate. In short, you learn how to apply JavaScript solutions to problems faced by web developers everywhere.

WHO THIS BOOK IS FOR

This book is aimed at three groups of readers:

Experienced developers familiar with object-oriented programming who are looking to learn JavaScript as it relates to traditional OO languages such as Java and C++

Web application developers attempting to enhance the usability of their websites and web applications

Novice JavaScript developers aiming to better understand the language

In addition, familiarity with the following related technologies is a strong indicator that this book is for you:

Compiled languages such as Java, C++, and Rust

Interpreted languages such as Python, PHP, and Ruby

HTML and CSS

This book is not aimed at beginners lacking a basic computer science background or those looking to add some simple user interactions to websites. These readers should instead refer to A Smarter Way to Learn JavaScript by Mark Myers (ASmarterWayToLearn.com, 2014).

WHAT THIS BOOK COVERS

Professional JavaScript for Web Developers, fifth edition, provides a developer-level introduction, along with the more advanced and useful features of JavaScript.

The book begins with an exploration of how JavaScript originated and evolved into what it is today. A detailed discussion of the components that make up a JavaScript implementation follows, with specific focus on standards such as ECMAScript and the Document Object Model (DOM).

Building on that base, the book moves on to cover basic concepts of JavaScript, including classes, promises, iterators, and proxies. This is followed by an in-depth examination of events, animations, forms, errors, and JSON.

The last part of the book is focused on the newest and most important additions to the language. This includes fetch, modules, web workers, service workers, and a collection of emerging APIs.

HOW THIS BOOK IS STRUCTURED

This book comprises the following chapters:

What Is JavaScript?—

Explains the origins of JavaScript: where it came from, how it evolved, and what it is today. Concepts introduced include the relationship between JavaScript and ECMAScript, the Document Object Model (DOM), and the Browser Object Model (BOM). A discussion of the relevant standards from the European Computer Manufacturer's Association (ECMA) and the World Wide Web Consortium (W3C) is also included.

JavaScript in HTML—

Examines how JavaScript is used in conjunction with HTML to create dynamic web pages. Introduces the various ways of embedding JavaScript into a page and includes a discussion surrounding the JavaScript content-type and its relationship to the

<script>

element.

Language Basics—

Introduces basic language concepts, including syntax and flow control statements. Explains the syntactic similarities of JavaScript and other C-based languages and points out the differences. Type coercion is introduced as it relates to built-in operators. Covers all language primitives, including the

Symbol

type.

Variables, Scope, and Memory—

Explores how variables are handled in JavaScript given their loosely typed nature. A discussion of the differences between primitive and reference values is included, as is information about execution context as it relates to variables. Also, a discussion about garbage collection in JavaScript covers how memory is reclaimed when variables go out of scope.

Basic Reference Types—

Covers all of the details regarding JavaScript's built-in reference types, such as

Date

,

Regexp

, primitives, and primitive wrappers. Each reference type is discussed both in theory and in how they relate to browser implementations.

Advanced Reference Types—

Continues the book's coverage of built-in reference types with

Object

,

Array

,

Map

,

WeakRef

,

WeakMap

,

Set

, and

WeakSet

.

Iterators and Generators—

Introduces iterators and generators and discusses both in terms of their most fundamental behavior as well as how they are used in relation to existing language constructs.

Objects, Classes, and Object-Oriented Programming—

Explains how to use classes and object-oriented programming in JavaScript. Begins with an in-depth discussion of the JavaScript Object type and continues into coverage of prototypal inheritance. Following this is a complete discussion of classes and how they are a close sibling of prototypal inheritance.

Proxies and Reflect—

Introduces two closely related concepts: Proxy and the Reflect API. These can be used to intercept and shim additional behavior into fundamental operations within the language.

Functions—

Explores one of the most powerful aspects of JavaScript: function expressions. Topics include closures, the

this

object, the module pattern, the creation of private object members, arrow functions, default parameters, and spread operators.

Promises and Async/Await—

Introduces two new closely related asynchronous programming constructs: the

Promise

type and

async/await

. The chapter begins with a discussion of the asynchronous JavaScript paradigm and continues into coverage of how promises are used and their relationship to async functions.

The Browser Object Model—

Introduces the Browser Object Model (BOM), which is responsible for objects allowing interaction with the browser itself. Each of the BOM objects is covered, including window, document, location, navigator, and screen.

The Document Object Model—

Introduces the Document Object Model (DOM) objects available in JavaScript as defined in DOM Level 1. Features an in-depth exploration of the entire DOM and how it allows developers to manipulate a page.

DOM Extensions—

Explains how other APIs, as well as the browsers themselves, extend the DOM with more functionality such as the Selectors API, the Element Traversal API, and HTML5 extensions. Discusses how DOM Levels 2 and 3 augmented the DOM with additional properties, methods, and objects. Includes coverage of DOM4 additions such as resize, intersection, and mutation observers.

Events—

Explains the nature of events in JavaScript, where they originated, and how the DOM redefined how events should work.

Animation and Graphics with Canvas—

Discusses the

<canvas>

tag and how to use it to create on-the-fly graphics. Both the 2D context and the WebGL (3D) context are covered, providing you with a good starting point for creating animations and games. Includes coverage of both WebGL1 and WebGL2.

Scripting Forms—

Explores using JavaScript to enhance form interactions and work around browser limitations. Discussion focuses on individual form elements such as text boxes and select boxes and on data validation and manipulation.

JavaScript APIs—

Covers an assortment of JavaScript APIs, including Atomics, Encoding, File, Blob, Notifications, Streams, Timing, Web Components, and Web Cryptography.

Error Handling and Debugging—

Discusses how browsers handle errors in JavaScript code and presents several ways to handle errors. Debugging tools and techniques are also discussed for each browser, including recommendations for simplifying the debugging process.

JSON—

Introduces the JSON data format. Discusses browser-native JSON parsing and serialization as well as security considerations when using JSON.

Network Requests and Remote Resources

—Explores all of the most ways that data and assets are requested by the browser via the Fetch API.

Client-Side Storage

—Discusses how to detect when an application is offline and provides various techniques for storing data on the client machine. Begins with a discussion of the most commonly supported feature, cookies, and then discusses newer functionality such as Web Storage and IndexedDB.

Modules

—Discusses the module pattern and its implications on codebases. Following this, the chapter covers module loaders such as CommonJS, AMD, and UMD. Ends with detailed coverage on the ECMAScript module pattern and how to use it properly.

Workers

—Covers dedicated workers, shared workers, and service workers in-depth. Includes a discussion of how workers behave both at the operating system and browser level, as well as strategies for how best to use the various types of workers.

Best Practices

—Explores approaches to working with JavaScript in an enterprise environment. Techniques for better maintainability are discussed, including coding techniques, formatting, and general programming practices. The chapter also covers execution performance and introduces several techniques for speed optimization. Last, the chapter covers deployment issues, including how to create a build process.

WHAT YOU NEED TO USE THIS BOOK

To run the samples in the book, you need the following:

Any modern operating system, such as Windows, Linux, or Mac OS

Any modern browser, such as Chrome, Firefox, Edge, Safari, or Opera

The complete source code is available for download from www.wiley.com/go/projavascript5e

1What Is JavaScript?

WHAT'S IN THIS CHAPTER?

Review of JavaScript history

What JavaScript is

How JavaScript and ECMAScript are related

The different versions of JavaScript

DOWNLOADS FOR THIS CHAPTER

Please note that all the code examples for this chapter are available as a part of this chapter's code download on the book's website at www.wiley.com/go/projavascript5e.

When JavaScript first appeared in 1995, its main purpose was to handle some of the input validation that had previously been left to server-side languages such as Perl. Prior to that time, a round-trip to the server was needed to determine if a required field had been left blank or an entered value was invalid. Netscape Navigator sought to change that with the introduction of JavaScript. The capability to handle some basic validation on the client was an exciting new feature at a time when use of telephone modems was widespread. The associated slow speeds turned every trip to the server into an exercise in patience.

Since that time, JavaScript has grown into an important feature of every major web browser on the market. No longer bound to simple data validation, JavaScript now interacts with nearly all aspects of the browser window and its contents. JavaScript is recognized as a full programming language, capable of complex calculations and interactions, including closures, anonymous (lambda) functions, and even metaprogramming. JavaScript has become such an important part of the web that even alternative browsers, including those on mobile phones and those designed for users with disabilities, support it. Even Microsoft, with its own client-side scripting language called VBScript, ended up including its own JavaScript implementation in Internet Explorer from its earliest version.

The rise of JavaScript from a simple input validator to a powerful programming language could not have been predicted. JavaScript is at once a very simple and very complicated language that takes minutes to learn but years to master. To begin down the path to using JavaScript's full potential, it is important to understand its nature, history, and limitations.

A SHORT HISTORY

As the web gained popularity, a gradual demand for client-side scripting languages developed. At the time, most Internet users were connecting over a 28.8 kbps modem even though web pages were growing in size and complexity. Adding to users' pain was the large number of round-trips to the server required for simple form validation. Imagine filling out a form, clicking the Submit button, waiting 30 seconds for processing, and then being met with a message indicating that you forgot to complete a required field. Netscape, at that time on the cutting edge of technological innovation, began seriously considering the development of a client-side scripting language to handle simple processing.

In 1995, a Netscape developer named Brendan Eich began developing a scripting language called Mocha (later renamed as LiveScript) for the release of Netscape Navigator 2. The intention was to use it both in the browser and on the server, where it was to be called LiveWire.

Netscape entered into a development alliance with Sun Microsystems to complete the implementation of LiveScript in time for release. Just before Netscape Navigator 2 was officially released, Netscape changed LiveScript's name to JavaScript to capitalize on the buzz that Java was receiving from the press.

Because JavaScript 1.0 was such a hit, Netscape released version 1.1 in Netscape Navigator 3. The popularity of the fledgling web was reaching new heights, and Netscape had positioned itself to be the leading company in the market. At this time, Microsoft decided to put more resources into a competing browser named Internet Explorer. Shortly after Netscape Navigator 3 was released, Microsoft introduced Internet Explorer 3 with a JavaScript implementation called JScript (so called to avoid any possible licensing issues with Netscape). This major step for Microsoft into the realm of web browsers in August 1996 is now a date that lives in infamy for Netscape, but it also represented a major step forward in the development of JavaScript as a language.

Microsoft's implementation of JavaScript meant that there were two different JavaScript versions floating around: JavaScript in Netscape Navigator and JScript in Internet Explorer. Unlike C and many other programming languages, JavaScript had no standards governing its syntax or features, and the two different versions only highlighted this problem. With industry fears mounting, it was decided that the language must be standardized.

In 1997, JavaScript 1.1 was submitted to the European Computer Manufacturers Association (Ecma) as a proposal. Technical Committee #39 (TC39) was assigned to “standardize the syntax and semantics of a general purpose, cross-platform, vendor-neutral scripting language” (www.ecma-international.org/memento/TC39.htm). Made up of programmers from Netscape, Sun, Microsoft, Borland, NOMBAS, and other companies with interest in the future of scripting, TC39 met for months to hammer out ECMA-262, a standard defining a new scripting language named ECMAScript (often pronounced as “ek-ma-script”).

The following year, the International Organization for Standardization and International Electrotechnical Commission (ISO/IEC) also adopted ECMAScript as a standard (ISO/IEC-16262). Since that time, browsers have tried, with varying degrees of success, to use ECMAScript as a basis for their JavaScript implementations.

JAVASCRIPT IMPLEMENTATIONS

Though JavaScript and ECMAScript are often used synonymously, JavaScript is much more than just what is defined in ECMA-262. Indeed, a complete JavaScript implementation is made up of the following three distinct parts (see Figure 1.1):

The Core (ECMAScript)

The Document Object Model (DOM)

The Browser Object Model (BOM)

FIGURE 1.1: Components of JavaScript

ECMAScript

ECMAScript, the language defined in ECMA-262, isn't tied to web browsers. In fact, the language has no methods for input or output whatsoever. ECMA-262 defines this language as a base upon which more-robust scripting languages may be built. Web browsers are just one host environment in which an ECMAScript implementation may exist. A host environment provides the base implementation of ECMAScript and implementation extensions designed to interface with the environment itself. Extensions, such as the Document Object Model (DOM), use ECMAScript's core types and syntax to provide additional functionality that's more specific to the environment. Other host environments include NodeJS, a server-side JavaScript platform, and the increasingly obsolete Adobe Flash.

What exactly does ECMA-262 specify if it doesn't reference web browsers? On a very basic level, it describes the following parts of the language:

Syntax

Types

Statements

Keywords

Reserved words

Operators

Global objects

ECMAScript is simply a description of a language implementing all of the facets described in the specification, and JavaScript implements ECMAScript.

ECMAScript Editions

The different versions of ECMAScript are defined as editions (referring to the edition of ECMA-262 in which that particular implementation is described). The first edition of ECMA-262 was essentially the same as Netscape's JavaScript 1.1 but with all references to browser-specific code removed and a few minor changes: ECMA-262 required support for the Unicode standard (to support multiple languages) and that objects be platform-independent (Netscape JavaScript 1.1 actually had different implementations of objects, such as the Date object, depending on the platform). This was a major reason why JavaScript 1.1 and 1.2 did not conform to the first edition of ECMA-262.

The second edition of ECMA-262 was largely editorial. The standard was updated to get into strict agreement with ISO/IEC-16262 and didn't feature any additions, changes, or omissions. ECMAScript implementations typically don't use the second edition as a measure of conformance.

The third edition of ECMA-262 was the first real update to the standard. It provided updates to string handling, the definition of errors, and numeric outputs. It also added support for regular expressions, new control statements, try-catch exception handling, and small changes to better prepare the standard for internationalization. To many, this marked the arrival of ECMAScript as a true programming language.

The fourth edition of ECMA-262 was a complete overhaul of the language. In response to the popularity of JavaScript on the web, developers began revising ECMAScript to meet the growing demands of web development around the world. In response, Ecma TC39 reconvened to decide the future of the language. The resulting specification defined an almost completely new language based on the third edition. The fourth edition includes strongly typed variables, new statements and data structures, true classes and classical inheritance, and new ways to interact with data.

As an alternate proposal, a specification called “ECMAScript 3.1,” was developed as a smaller evolution of the language by a subcommittee of TC39, who believed that the fourth edition was too big of a jump for the language. The result was a smaller proposal with incremental changes to ECMAScript that could be implemented on top of existing JavaScript engines. Ultimately, the ES3.1 subcommittee won over support from TC39, and the fourth edition of ECMA-262 was abandoned before officially being published.

ECMAScript 3.1 became ECMA-262, fifth edition, and was officially published on December 3, 2009. The fifth edition sought to clarify perceived ambiguities of the third edition and introduce additional functionality. The new functionality includes a native JSON object for parsing and serializing JSON data, methods for inheritance and advanced property definition, and the inclusion of a new strict mode that slightly augments how ECMAScript engines interpret and execute code. The fifth edition saw a maintenance revision in June 2011; this was merely for corrections in the specification and introduced no new language or library features.

The sixth edition of ECMA-262—colloquially referred to as ES6, ES2015, or ES Harmony—was published in June 2015, and contained arguably the most important collection of enhancements to the specification since its inception. ES6 added formal support for classes, modules, iterators, generators, arrow functions, promises, reflection, proxies, and a host of new data types.

ES6 also marked the beginning of annual releases of ECMAScript editions. As a result, ECMAScript editions gradually ceased to be referred to by an incrementing integer (ES5, ES6) and began to be referred to by the year of their release (ES2020, ES2021). Recent editions have included features such as additional string and array methods, async/await, dynamic module imports, and new numerical types.

What Does ECMAScript Conformance Mean?

ECMA-262 lays out the definition of ECMAScript conformance. To be considered an implementation of ECMAScript, an implementation must do the following:

Support all “types, values, objects, properties, functions, and program syntax and semantics” as they are described in ECMA-262.

Support the Unicode character standard.

Additionally, a conforming implementation may do the following:

Add “additional types, values, objects, properties, and functions” that are not specified in ECMA-262. ECMA-262 describes these additions as primarily new objects or new properties of objects not given in the specification.

Support “program and regular expression syntax” that is not defined in ECMA-262 (meaning that the built-in regular-expression support is allowed to be altered and extended).

These criteria give implementation developers a great amount of power and flexibility for developing new languages based on ECMAScript, which partly accounts for its popularity.

The Document Object Model

The Document Object Model (DOM) is an application programming interface (API) for XML that was extended for use in HTML. The DOM maps out an entire page as a hierarchy of nodes. Each part of an HTML or XML page is a type of node containing different kinds of data. Consider the following HTML page:

<html>

<head>

<title>Sample Page</title>

</head>

<body>

<p> Hello World!</p>

</body>

</html>

This code can be diagrammed into a hierarchy of nodes using the DOM (see Figure 1.2).

FIGURE 1.2: Example DOM node hierarchy

By creating a tree to represent a document, the DOM allows developers an unprecedented level of control over its content and structure. Nodes can be removed, added, replaced, and modified easily by using the DOM API.

Why the DOM Is Necessary

With Internet Explorer 4 and Netscape Navigator 4 each supporting different forms of Dynamic HTML (DHTML), developers for the first time could alter the appearance and content of a web page without reloading it. This represented a tremendous step forward in web technology but also a huge problem. Netscape and Microsoft went separate ways in developing DHTML, thus ending the period when developers could write a single HTML page that could be accessed by any web browser.

It was decided that something had to be done to preserve the cross-platform nature of the web. The fear was that if someone didn't rein in Netscape and Microsoft, the web would develop into two distinct factions that were exclusive to targeted browsers. It was then that the World Wide Web Consortium (W3C), the body charged with creating standards for web communication, began working on the DOM.

DOM Levels

DOM Level 1 became a W3C recommendation in October 1998. It consisted of two modules: the DOM Core, which provided a way to map the structure of an XML-based document to allow for easy access to and manipulation of any part of a document, and the DOM HTML, which extended the DOM Core by adding HTML-specific objects and methods.

NOTE that the DOM is not JavaScript-specific and indeed has been implemented in numerous other languages. For web browsers, however, the DOM has been implemented using ECMAScript and now makes up a large part of the JavaScript language.

Whereas the goal of DOM Level 1 was to map out the structure of a document, the aims of DOM Level 2 were much broader. This extension of the original DOM added support for mouse and user-interface events (long supported by DHTML), ranges, and traversals (methods to iterate over a DOM document), and support for Cascading Style Sheets (CSS) through object interfaces. The original DOM Core introduced in Level 1 was also extended to include support for XML namespaces.

DOM Level 2 introduced the following new modules of the DOM to deal with new types of interfaces:

DOM views

—Describes interfaces to keep track of the various views of a document (the document before and after CSS styling, for example)

DOM events

—Describes interfaces for events and event handling

DOM style

—Describes interfaces to deal with CSS-based styling of elements

DOM traversal and range

—Describes interfaces to traverse and manipulate a document tree

DOM Level 3 further extends the DOM with the introduction of methods to load and save documents in a uniform way (contained in a new module called DOM Load and Save) and methods to validate a document (DOM Validation). In Level 3, the DOM Core is extended to support all of XML 1.0, including XML Infoset, XPath, and XML Base.

Presently, the W3C no longer maintains the DOM as a set of levels, but rather as the DOM Living Standard, snapshots of which are termed DOM4. Among its introductions is the addition of Mutation Observers to replace Mutation Events.

NOTE When reading about the DOM, you may come across references to DOM Level 0. Note that there is no standard called DOM Level 0; it is simply a reference point in the history of the DOM. DOM Level 0 is considered to be the original DHTML supported in Internet Explorer 4.0 and Netscape Navigator 4.0.

Other DOMs

Aside from the DOM Core and DOM HTML interfaces, several other languages have had their own DOM standards published. The languages in the following list are XML-based, and each DOM adds methods and interfaces unique to a particular language:

Scalable Vector Graphics (SVG) 1.0

Mathematical Markup Language (MathML) 1.0

Synchronized Multimedia Integration Language (SMIL)

Additionally, other languages have developed their own DOM implementations, such as Mozilla's XML User Interface Language (XUL). However, only the languages in the preceding list are standard recommendations from W3C.

The Browser Object Model

The Internet Explorer 3 and Netscape Navigator 3 browsers featured a Browser Object Model (BOM) that allowed access and manipulation of the browser window. Using the BOM, developers can interact with the browser outside of the context of its displayed page. What made the BOM truly unique, and often problematic, was that it was the only part of a JavaScript implementation that had no related standard. This changed with the introduction of HTML5, which sought to codify much of the BOM as part of a formal specification. Thanks to HTML5, a lot of the confusion surrounding the BOM has dissipated.

Primarily, the BOM deals with the browser window and frames, but generally any browser-specific extension to JavaScript is considered to be a part of the BOM. The following are some such extensions:

The capability to pop up new browser windows

The capability to move, resize, and close browser windows

The navigator object, which provides detailed information about the browser

The location object, which gives detailed information about the page loaded in the browser

The screen object, which gives detailed information about the user's screen resolution

The performance object, which gives detailed information about the browser's memory consumption, navigational behavior, and timing statistics

Support for cookies

Custom objects such as

XMLHttpRequest

Because no standards existed for the BOM for a long time, each browser has its own implementation. There are some de facto standards, such as having a window object and a navigator object, but each browser defines its own properties and methods for these and other objects. With HTML5 now available, the implementation details of the BOM are expected to grow in a much more compatible way. A detailed discussion of the BOM is included in the Chapter 12, “The Browser Object Model.”

SUMMARY

JavaScript is a scripting language designed to interact with web pages and is made up of the following three distinct parts:

ECMAScript, which is defined in ECMA-262 and provides the core functionality

The Document Object Model (DOM), which provides methods and interfaces for working with the content of a web page

The Browser Object Model (BOM), which provides methods and interfaces for interacting with the browser

There are varying levels of support for the three parts of JavaScript across the five major web browsers (Edge, Firefox, Chrome, Safari, and Opera). Support for recent ECMAScript features is generally good across all browsers. Support for the DOM varies, but Level 3 compliance is increasingly normative. The BOM, codified in HTML5, can vary from browser to browser, though there are some commonalities that are assumed to be available.

2JavaScript in HTML

WHAT'S IN THIS CHAPTER?

Using the

<script>

element

Comparing inline and external scripts

Examining how document modes affect JavaScript

Preparing for JavaScript-disabled experiences

DOWNLOADS FOR THIS CHAPTER

Please note that all the code examples for this chapter are available as a part of this chapter’s code download on the book’s website at www.wiley.com/go/projavascript5e.

The introduction of JavaScript into web pages immediately ran into the web's predominant language, HTML. As part of its original work on JavaScript, Netscape tried to figure out how to make JavaScript coexist in HTML pages without breaking those pages' rendering in other browsers. Through trial, error, and controversy, several decisions were finally made and agreed upon to bring universal scripting support to the web. Much of the work done in these early days of the web has survived and become formalized in the HTML specification.

THE <SCRIPT> ELEMENT

The primary method of inserting JavaScript into an HTML page is via the <script> element. This element was created by Netscape and first implemented in Netscape Navigator 2. It was later added to the formal HTML specification. There are eight attributes for the <script> element:

async

—Optional. Indicates that the script should begin downloading immediately but should not prevent other actions on the page such as downloading resources or waiting for other scripts to load. Valid only for external script files.

charset

—Optional. The character set of the code specified using the

src

attribute. This attribute is rarely used because most browsers don't honor its value.

crossorigin

—Optional. Configures the CORS settings for the associated request; by default, CORS is not used at all.

crossorigin="anonymous"

will configure the request for the file to not have the credentials flag set.

crossorigin="use-credentials"

will set the credentials flag, meaning the outgoing request will include credentials.

defer

—Optional. Indicates that the execution of the script can safely be deferred until after the document's content has been completely parsed and displayed. Valid only for external scripts.

integrity

—Optional. Allows for verification of Subresource Integrity (SRI) by checking the retrieved resource against a provided cryptographic signature. If the signature of the retrieved resource does not match that specified by this attribute, the page will error and the script will not execute. This is useful for ensuring that a Content Delivery Network (CDN) is not serving malicious payloads.

language

—Deprecated. Originally indicated the scripting language being used by the code block (such as “JavaScript,” “JavaScript1.2,” or “VBScript”). Most browsers ignore this attribute; it should not be used.

src

—Optional. Indicates an external file that contains code to be executed.

type

—Optional. Replaces language; indicates the content type (also called MIME type) of the scripting language being used by the code block. Traditionally, this value has always been “

text/javascript

,” though both “text/javascript” and “text/ecmascript” are deprecated. JavaScript files are typically served with the “application/x-javascript” MIME type even though setting this in the type attribute may cause the script to be ignored. Other valid values are “application/javascript” and “application/ecmascript.” If the value is “module,” the code is treated as an ES6 module and only then is eligible to use the import and export keywords.

There are two ways to use the <script> element: embed JavaScript code directly into the page or include JavaScript from an external file.

To include inline JavaScript code, place JavaScript code inside the <script> element directly, as follows:

<script>

function sayHi() {

console.log("Hi!");

}

</script>

The JavaScript code contained inside a <script> element is interpreted from top to bottom. In the case of this example, a function definition is interpreted and stored inside the interpreter environment. The rest of the page content is not loaded and/or displayed until after all of the code inside the <script> element has been evaluated.

When using inline JavaScript code, keep in mind that you cannot have the string “</script>” anywhere in your code. For example, the following code causes an error when loaded into a browser:

<script>

function sayScript() {

console.log("</script>");

}

</script>

Because of the way that inline scripts are parsed, the browser sees the string "</script>" as if it were the closing </script> tag. This problem can be avoided easily by escaping the "/" character, as in this example:

<script>

function sayScript() {

console.log("<\/script>");

}

</script>

The changes to this code make it acceptable to browsers and won't cause any errors.

To include JavaScript from an external file, the src attribute is required. The value of src is a URL linked to a file containing JavaScript code, like this:

<script src="example.js"></script>

In this example, an external file named example.js is loaded into the page. The file itself need only contain the JavaScript code that would occur between the opening <script> and closing </script> tags. As with inline JavaScript code, processing of the page is halted while the external file is interpreted. (There is also some time taken to download the file.) In XHTML documents, you can omit the closing tag, as in this example:

<script src="example.js"/>

This syntax should not be used in HTML documents because it is invalid HTML and won't be handled properly by some browsers, most notably Internet Explorer.

NOTE By convention, external JavaScript files have a.jsextension. This is not a requirement because browsers do not check the file extension of included JavaScript files. This leaves open the possibility of dynamically generating JavaScript code using a server-side scripting language, or for in-browser transpilation into JavaScript from a JavaScript extension language such as TypeScript or React's JSX. Keep in mind, though, that servers often use the file extension to determine the correct MIME type to apply to the response. If you don't use a.jsextension, double-check that your server is returning the correct MIME type.

It's important to note that a <script> element using the src attribute should not include additional JavaScript code between the <script> and </script> tags. If both are provided, the script file is downloaded and executed while the inline code is ignored.

One of the most powerful and most controversial parts of the <script> element is its ability to include JavaScript files from outside domains. Much like an <img> element, the <script> element's src attribute may be set to a full URL that exists outside the domain on which the HTML page exists, as in this example:

<script src="http://www.somewhere.com/afile.js"></script>

When the browser goes to resolve this resource, it will send a GET request to the path specified in the src attribute to retrieve the resource—presumably a JavaScript file. This initial request is not subject to the browser's cross-origin restrictions, but any JavaScript returned and executed will be. Of course, this request is still subject to the HTTP/HTTPS protocol of the parent page.

Code from an external domain will be loaded and interpreted as if it were part of the page that is loading it. This capability allows you to serve up JavaScript from various domains, if necessary. Be careful, however, if you are referencing JavaScript files located on a server that you don't control. A malicious programmer could, at any time, replace the file. When including JavaScript files from a different domain, make sure you are the domain owner, or the domain is owned by a trusted source. The <script> tag's integrity attribute gives you a tool to defend against this.

Regardless of how the code is included, the <script> elements are interpreted in the order in which they appear in the page so long as the defer and async