Click on the asynchronous book, the top public account

Every day to share with you IT good books technology dry goods workplace knowledge

This article includes the following:

  • Life cycle steps for Web applications

  • Processing from HTML code to Web pages

  • The execution order of JavaScript code

  • Interacting with events

  • Event loop

Our exploration of JavaScript begins with a client-side Web application, whose code also runs on a browser-provided engine. In order to lay a solid foundation for future learning of JavaScript language and browser platform, we should first understand the life cycle of Web applications, especially the execution of JavaScript code in all aspects of the life cycle.

This article explores the entire life cycle of a client-side Web application, starting with page requests, through the different kinds of user interactions, and finally until the page is closed. First let’s look at how the page is built from HTML code. Then we’ll focus on the execution of the JavaScript code, which provides a lot of interaction for our pages. Finally, we’ll look at how events are handled in response to user actions. In this series, we’ll explore many of the basic concepts of Web applications, such as DOM (a structured representation of a Web page) and event loops (which determine how an application handles events). Let’s start learning!

You know what?

  • Will browsers always render a page based on a given HTML?

  • How many events can a Web application handle at a time?

  • Why do browsers use event queues to handle events?

1.1 Lifecycle Overview

The life cycle of a typical client-side Web application begins when a user enters a string of urls into the browser address bar, or clicks a link. For example, we want to go to Google’s home page and look up a term. First we enter the URL, www.google.com, as shown in Figure 1.1.

Figure 1.1 The client Web application cycle starts with the user specifying a Web site address (or clicking a link) and consists of two steps: page construction and event handling

From the user’s perspective, the browser constructs the request to the server (No. 2), which processes the request (No. 3) and forms a response that typically consists of HTML, CSS, and JavaScript code. When the browser receives the response (number 4), our client application begins its life cycle. Since a client Web application is a graphical user interface (GUI) application, its life cycle is similar to that of any other GUI application (such as a standard desktop or mobile application), and its execution steps are as follows:

1. Page building – creating the user interface;

2. Event processing – Enter a loop (no. 5) to wait for an event (No. 6) to occur and invoke the event handler.

The application life cycle ends when the user closes or leaves the page (number 7). Now let’s look at a simple example program that displays a message every time the user moves the mouse or clicks on a page. This example will be used throughout this article, as shown in Listing 1.1.

Listing 1.1 is a Web application applet with a GUI that describes the response to an event

Copy the code

1
2 3 4

Web app lifecycle 5

9 10 11

12 13 35 36

Listing 1.1 starts by defining two CSS rules, #first and #second, which specify the text colors of the elements whose ids are first and second (thus making it easier to distinguish between the two). We then define a list element with the id first:

Copy the code

1<ul id=”first”></ul>

Then define an addMessage function that creates a new list item element each time it is called, sets its literal content, and appends it to an existing element:

Function addMessage (element, message) {2 var messageElement = document.createElement (“li”); 3 messageElement.textContent = message; 4 appendChild (messageElement); 5}

Get the element with ID FIRST from the document using the built-in method getElementById, as shown below, and then add a message to that element to tell you that the page is loading:

1var first = document.getelementbyid (“first”); 2addMessage (first, “Page loading”);

We then define a list element, this time with the ID attribute second:

Copy the code

1<ul id=”second”></ul>

Finally, attach the two event handlers to the Body of the Web page. Each time the user moves the mouse, the mouse-movement Event handler is executed, which then calls the addMessage method, adding the words “Event: Mousemove” to the second list element.

1 document. Body. AddEventListener (” mousemove “, function () {var second = 2 document. The getElementById (” second “); 3 addMessage (second, “Event: mousemove”); 4});

We also registered a click Event handler that prints the message “Event: Click” every time the user clicks on the page and adds it to the second list element.

1 document. Body. AddEventListener (” click “, function () {var second = 2 document. The getElementById (” second “); 3 addMessage (second, “Event: click”); 4});

The running results and interactions of the application are shown in Figure 1.2.

We will also use this example to show the differences between phases of the Web application life cycle. Let’s start with the page construction phase.

After the code in Figure 1.2 and Listing 1.1 runs, the user’s actions are logged as messages

1.2 Page construction phase

Before a Web application can be displayed or interacted with, its pages must be built from the responses (usually HTML, CSS, and JavaScript code) that the server gets. The goal of the page construction phase is to build the UI of the Web application, which consists of two steps:

1. Parsing HTML code and building a document Object Model (DOM);

2. Execute JavaScript code.

Step 1 is executed while the browser is processing the HTML node, and Step 2 is executed when the HTML is parsed to a special type of node called a script node (a node that contains or references JavaScript code). These two steps alternate several times during the page construction phase, as shown in Figure 1.3.

Figure 1.3 The page construction phase begins when the browser receives the page code. Its execution is divided into two steps: HTML parsing and DOM building, and the execution of JavaScript code

1.2.1HTML parsing and DOM construction

The page build phase begins when the browser receives THE HTML code and forms the basis for the browser to build the page UI. Build the DOM by parsing the RECEIVED HTML code, building each HTML element. In this structured representation of HTML, each HTML element is treated as a node. As shown in Figure 1.4, the sample page builds the DOM until it hits the first script element.

Notice how the nodes in Figure 1.4 are organized so that all nodes have only one parent except for the first node, the HTML root node (number 1). For example, the parent of the head node (number 2) is an HTML node (number 1). At the same time, a node can have any number of children. For example, the HTML node (serial number 1) has two children: the head node (serial number 2) and the body node. Children of the same element are called siblings. (The head and body nodes are siblings.) Although the DOM is created from HTML and the two are closely related, it’s important to note that they are not the same. You can think of the HTML code as the blueprint for building the initial DOM of the browser page UI. To build each DOM correctly, the browser also fixes the problems it finds in the blueprint. Let’s look at the following example, shown in Figure 1.5.

Figure 1.4 When the browser encounters the first script element, it has created a DOM tree with multiple HTML elements (the node on the right)

Figure 1.5 shows a simple example of incorrect HTML code in which a paragraph element is mistakenly included in the head element of the page. The general purpose of the head element is to display general information about the page, such as the page title, character encoding, and external style scripts, rather than to define the content of the page, as in this example. The browser silently fixes the error, putting the paragraph element in the body element where the page content should be, and constructing the correct DOM (right in Figure 1.5).

Figure 1.5 The browser fixes the wrong HTML code

HTML specification and DOM specification

The current HTML version is HTML 5, can what are available through https://html.spec.whatwg.org/ to see the current version features. If you need easier to read the document, we recommend to you the Mozilla HTML 5 guide, through https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5 to check.

DOM, on the other hand, has been slower to evolve. The current DOM version is the DOM3, can through https://dom.spec.whatwg.org/ to view the standard. Also, Mozilla for DOM provides a report that can be view via https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model.

During the page construction phase, the browser encounters a special type of HTML element — a script element, which is used to include JavaScript code. Every time a script element is parsed, the browser stops building the DOM from the HTML and starts executing the JavaScript code.

1.2.2 Executing JavaScript Code

All JavaScript code contained in script elements is executed by the browser’s JavaScript engine, for example, the Spidermonkey engine for Firefox, the Chrome and Opera engines and the V8 engine for Edge (IE’s) Chakra engine. Since the main purpose of the code is to serve dynamic pages, the browser provides an API through the global object that the JavaScript engine can interact with and change the page content.

Global objects in JavaScript

The main global object that the browser exposes to the JavaScript engine is the Window object, which represents the window containing a page. The Window object is the way to access all other global objects, global variables (even user-defined objects), and browser apis. The most important property of the global Window object is document, which represents the DOM of the current page. Using this object, JavaScript code can alter the DOM in any way, including modifying or removing existing nodes, and creating and inserting new ones.

Let’s look at the code snippet shown in Listing 1.1:

Copy the code

1var first = document.getelementbyid (“first”);

This example uses the global Document object to select an element by ID and assign that element to the variable first. We can then use JavaScript code on the element to do various things to it, such as changing its literal content, modifying its attributes, dynamically creating and adding new child nodes, and even removing the element from the DOM.

The browser API

Throughout this article, we describe a series of browser-built objects and functions (for example, Window and Document). Unfortunately, all of the features supported by browsers are beyond the scope of JavaScript in this article. Fortunately, Mozilla provides support for us, at https://developer.mozilla.org/en-US/docs/Web/API, you can find the current state of the WebAPI interface.

With a basic understanding of the basic global objects provided by browsers, we can start to look at the two different ways in which types are defined in JavaScript code.

Different types of JavaScript code

We can roughly distinguish between two different types of JavaScript code: global code and functional code. Listing 1.2 will help you understand the difference between these two types of code.

Listing 1.2JavaScript global code and function code

1

The main difference between these two types of code is their location: code contained within a function is called function code, while code outside all functions is called global code.

The two types of code also execute differently (you’ll see some other differences later). Global code is automatically executed in a straightforward fashion by the JavaScript engine (more on that later), line by line whenever such code is encountered. For example, in Listing 1.2, the global code snippet defined in the addMessage function uses the built-in getElementById method to get the element with ID FIRST, and then calls the addMessage function, as shown in Figure 1.6, each time it is encountered.

Figure 1.6 program execution flow when executing JavaScript code

Conversely, if function code is to be executed, it must be called by other code: either global code (for example, addMessage is called because it was executed during the execution of the global code), other functions, or by the browser (more on that later).

Execute JavaScript code during the page construction phase

When the browser encounters a script node during the page build phase, it stops the HTML-to-DOM build and starts executing JavaScript code instead, that is, executing the global JavaScript code contained within the script element (and the function code called by the global code execution). Let’s look at an example in Listing 1.1.

Figure 1.7 shows the state of the DOM after the global JavaScript code has been executed. Let’s take a closer look at this implementation. We first define an addMessage function:

1

We then get an element from the DOM via the getElementById method on the global Document object:

Copy the code

1var first = document.getelementbyid (“first”);

This code is followed by a call to the function addMessage:

Copy the code

1addMessage (first, “Page loading”);

This code creates a new Li element, modifies its literal content, and inserts it into the DOM.

Figure 1.7 DOM structure in the page after executing the JavaScript code in the script element

In this example, JavaScript modifies the current DOM structure by creating a new element and inserting it into the DOM node. In general, JavaScript code can modify the DOM structure in any way: it can create new orders or remove existing DOM nodes. But it still can’t do things like select and modify nodes that haven’t been created yet. This is why script elements are placed at the bottom of the page. This way, we don’t have to worry about whether an HTML element is already loaded as a DOM.

Once the JavaScript engine executes the last line of JavaScript code in the script element (returned by the addMessage function in Figure 1.5), the browser exits JavaScript execution mode and builds the rest of the HTML as a DOM node. During this time, if the browser encounters a script element again, the HTML to DOM build is paused again, and the JavaScript runtime environment starts executing the rest of the JavaScript code. It is important to note that the JavaScript application remains global at this point. All global variables created by a user during the execution of a JavaScript code are normally accessed by JavaScript code in other script elements. The reason for this is that the global Window object exists for the lifetime of the page and stores all JavaScript variables on it. The next two steps alternate as long as there are unprocessed HTML elements and unexecuted JavaScript code.

1. Build HTML as DOM.

2. Execute JavaScript code.

Finally, when the browser has processed all the HTML elements, the page construction phase is over. The browser then moves on to the second part of the application life cycle: event handling.

1.3 Event Handling

A client-side Web application is a GUI application, which means it responds to different types of events, such as mouse movements, clicks, and keyboard presses. Therefore, JavaScript code executed during the page construction phase, in addition to affecting the global application state and modifying the DOM, registers event listeners (or handlers). This type of listener is executed by a browser call when an event occurs. With these event handlers, our applications have the ability to interact. Before diving into the details of registering event handlers, let’s walk through the general idea of event handlers.

1.3.1 Event Handler Overview

The core idea behind the browser execution environment is that only one piece of code can be executed at a time, the so-called single-threaded execution model. Imagine standing in line at a bank counter, each person entering a line to be called and “processed.” JavaScript, on the other hand, opens only one counter! When it is the turn of a customer (an event), only that customer can be processed.

All you need is one person at the sales counter (everyone is in line at this counter!). Your staff will handle your work and help you plan your finances for the year. When an event arrives, the browser needs to execute the corresponding event handler. There is no guarantee that users will always wait patiently for the next event to fire. So the browser needs a way to keep track of events that have occurred but not yet been processed. To achieve this, the browser uses event queues, as shown in Figure 1.8.

All generated events (whether user-generated, such as mouse movements or keyboard presses, or server-generated, such as Ajax events) are placed in the same event queue in the order in which they are detected by the browser. As shown in the middle of Figure 1.8, the process of event processing can be described as a simple flow chart.

  • The browser checks the event queue header;

  • If the browser does not detect the event in the queue, it continues to check;

  • If the browser detects an event in the queue header, it fetches the event and executes the appropriate event handler (if present). In this process, the remaining events wait patiently in the event queue until it is their turn to be processed.

Since only one event can be processed at a time, we have to pay extra attention to the total time it takes to process all events. Executing event handlers that take a lot of time to execute can make your Web application unresponsive! (If that doesn’t sound too clear, don’t worry, we’ll learn more about event loops in the future and see how they can hurt the performance of Web applications on feelings.)

Figure 1.8 The client Web application cycle starts with the user specifying a Web address (or clicking a link).

It consists of two steps: page building and event handling

Focus on the mechanism by which the browser places events in queues outside of the page construction and event processing phases. This process, which is important for determining when an event occurs and pushing it to the event queue, does not participate in the event processing thread.

Events are asynchronous

Events can occur in unpredictable times and sequences (forcing users to keypress or click in a certain order is very strange). Our processing of events, and the invocation of handler functions, is asynchronous. The following types of events occur in other types of events.

  • Browser events, such as when the page has finished loading or cannot load;

  • Network events, such as responses from the server (Ajax and server-side events);

  • User events, such as mouse clicks, mouse movements, and keyboard events;

  • Timer event when timeout expires or another interval is fired.

Most of the JavaScript code in a Web application is handling these events!

The concept of event handling is central to Web applications, and you’ll see it again and again in the examples in this article: code is built in advance to be executed at a later point in time. With the exception of global code, most of the code in the page will execute as a result of an event.

Before an event can be handled, the code must tell the browser that we want to handle a particular event. Let’s see how to register an event handler.

1.3.2 Registering event handlers

As mentioned earlier, event handlers are functions that we want to execute when a particular event occurs. To achieve this, we must tell the browser which event we want to process. This process is called registering event handlers. In a client-side Web application, there are two ways to register events.

  • By assigning a function to a particular property;

  • By using the built-in addEventListener method.

For example, write the following code to assign a function to a particular attribute onload on the window object:

Copy the code

1window.onload = function () {};

In this way, the event handler registers with the Load event (which is triggered when the DOM is ready and all built). (Don’t worry if you’re confused by the notation on the right-hand side of the assignment operator, we’ll cover the function in detail in a later section.) Similarly, if we want to register a handler for the click event on the body element in a document, we can type the following:

Copy the code

Document.body.onclick = function () {};

Assigning functions to special attributes is a simple and straightforward way to register event handlers. However, it is not recommended that you register event handlers in this way because of the disadvantage of registering only one event handler for an event. That is, you can accidentally overwrite the last event handler. Fortunately, there is an alternative: the addEventListener method lets us register as many events as we need. The following listing uses the example in Listing 1.3 to show you this handy usage.

Listing 1.3 registers the event handler

1 < script > 2 document. Body. AddEventListener (” mousemove “, Function () {⇽– var second = document.getelementById (“second”); 4 addMessage (second, “Event: mousemove”); 5}); 6 the document. The body. The addEventListener (” click “, Var second = document.getelementById (“second”); 8 addMessage (second, “Event: click”); 9}); 10

In this example, we use the built-in addEventListener method on an HTML element and specify the event type (mousemove event or Click) and the event handler in the function. This means that when the mouse is moved over the page, the browser calls this function to add a message to the list element with ID bit second, “Event: Mousemove “(similarly, when the body is clicked, “Event: Click” is added to the same element). Now that you’ve learned how to create event handlers, let’s recall the simple flowchart we saw earlier and take a closer look at how events are handled.

1.3.3 Handling Events

The main idea behind event handling is that when an event occurs, the browser invokes the corresponding event handler. As mentioned earlier, due to the single-threaded execution model, only one event can be processed at a time. Any subsequent events can only be processed after the current event handler has completed execution!

Let’s go back to the application in Listing 1.1. Figure 1.9 shows the execution when the user moves quickly and clicks the mouse.

Let’s see what happens here. In response to user actions, the browser places mouse movement and click events in the event queue in the order in which they occur: the first is the mouse movement event and the second is the click event number 1.

In the event processing phase, the event loop checks the queue, finds a mouse movement event in front of the queue, and executes the corresponding event handler number 2. When the mouse movement event handler completes processing, it is the turn of the click event waiting in the queue. When the last line of the mouse move event handler function has been executed, the JavaScript engine exits the event handler function, the mouse move event completes the sequence number 3, and the event loop checks the queue again. This time, at the front of the queue, the event loop finds the mouse click event and processes it. Once the click handler completes and there are no new events in the queue, the event loop continues to loop, waiting to process new incoming events. This loop continues until the user closes the Web application.

Figure 1.9 shows an example of the event processing phase in two events — mouse movement and click

We now have an overview of all the steps in the event processing phase. Let’s look at how this process affects the DOM (figure 1.10). The second list element, with ID second, is selected when the mouse moves the processor.

Figure 1.10 DOM tree structure of the instance application after mouse movement and mouse click events have been processed

Then add a new list item element number 1 by using addMessage, using the text “Event: Mousemove”. Once the mouse moves the handler, the event loop executes the click on the event handler, creating another list element number 2 that is appended to the second list element with ID Second.

With a clear understanding of the Web application client lifecycle, the next part of this article will focus on the JavaScript language and clarify the ins and outs of functions.

1.4 summary

  • The HTML code received by the browser serves as a blueprint for creating the DOM, which is the internal presentation stage of the client’s Web application structure.

  • We use JavaScript code to dynamically modify the DOM to bring dynamic behavior to the Web application.

  • The execution of a client-side Web application is divided into two phases.

    • The page build code is used to create the DOM, while the global JavaScript code is executed when aScript node is encountered. During this execution, JavaScript code can alter the current DOM to any degree, and it can register event handlers — functions that are executed when a particular event (for example, a mouse click or keyboard press) occurs. Registering event handlers is easy: use the built-in addEventListener method.

    • Event processing – Only one of several different events can be processed at a time, in the order in which the event was generated. The event processing phase relies heavily on the event queue, where all events are stored in the order in which they appear. The event loop checks the header of the practice queue, and if an event is detected, the corresponding event handler is called.

1.5 practice

1. What are the two life cycle phases of a client Web application?

2. What are the advantages of using the addEventListener method to register an event handler over assigning an event handler to an attribute of a particular element?

3. How many events can a JavaScript engine handle at one time?

4. In what order are the events in the event queue processed?

Copy the code

1 2

5


This article is excerpted from JavaScript Ninja Secrets, 2nd Edition

JavaScript Ninja Secrets, 2nd Edition

[美] John, Resig, Bear, Bibeault, Josip… the


Click on the cover to buy the paper book


The JavaScript language is important, and there are many technical books on it, but to date there is no in-depth, comprehensive introduction to the important parts of the JavaScript language (functions, closures, and prototypes), nor is there a book on cross-browser coding. This book, written by the creators of the jQuery library, is an in-depth look at the JavaScript language.

JavaScript Ninja Secrets (2nd Edition) uses real-world examples to clearly explain each of the core concepts and techniques. The book introduces you to the core concepts of JavaScript, such as functions, closures, objects, stereotypes, and promises, as well as JavaScript apis, including the DOM, events, and timers. You’ll learn testing, cross-browser development, all the skills that advanced JavaScript developers should have.

Stretch recommended

A blockbuster book for January 2018

Primary school students start learning Python, the closest programming language to AI: A Wave of Python books from Amway

Policy warming: Everyone is learning big data, a wave of good books recommended

Selenium Automation is a Python based test book for Selenium

Eight new books. Send one you like

AI | classic books (introduction to artificial intelligence which books to read?

Click on keywords to read more new books:

Python | | machine learning Kotlin Java | | | | mobile development robots contests | Web front-end | book list

Long press the QR code, you can follow us yo

I share IT articles with you every day.


If you reply “follow” in the background of “Asynchronous books”, you can get 2000 online video courses for free. Recommend friends to pay attention to according to the prompts to get a gift book link, free of charge asynchronous books. Come and join us!

Scan the qr code above and reply “follow” to participate in the event!

















Buy JavaScript Ninja Secrets 2nd Edition

Read the original