[WebKit] parse criptcore-Basic (4) page parsing and JavaScript element execution

Source: Internet
Author: User

In many cases, we have already introduced how Javascript is executed in the browser. Here we will introduce how WebKit is implemented. It mainly involves JS async, defer, and code implementation of parsing and executing common scripts.


1. Summary

First, it briefly describes how the Browser executes Javascript. First, the browser's document parser will initiate a download when it encounters <SCRIPT> (the script content does not need to be downloaded if it is on the page ). The execution method varies according to different situations:

. Async (The async attribute is enabled in the script tag)

This is an asynchronous execution. The document parser is not blocked during the download process. The execution starts after the Javascript is loaded.

. Defer (the defer attribute is enabled in the script tag)

This operation is postponed. The document parser will not be blocked during the download process and will be executed only after the document parser completes page parsing.

. Reference external script filesThe document parser is blocked until the script is executed.

. If style sheet is not successfully parsed on the pageThe script is blocked until the style sheet is downloaded and parsed.


Because blocking will seriously affect the page resolution performance, it is also the focus of browser optimization:

A. The introduction of preload handler in WebKit allows you to attempt to process subsequent resources during download. [LINK] However, as the network speed increases, the optimization effect should gradually decrease.

B. Firefox implements asynchronous HTML Parsing. WebKit also implemented a lightweight version in early 2013 (only multithreading of tokenizer ).

2. Main Functions of JavaScript 2.1 executed in WebCore

The parsing and execution of Javascript elements in WebCore divide related classes into two main categories:

Page parsing and JS execution.


Page resolution categoryIt focuses on managing Script Creation and planning execution policies during HTML file parsing page. This part of detailed functions is complex and has specific definitions in W3C. The implementation of WebKit is also described in the reference section.

JS execution typeManages JS execution environments based on document and frame, and executes JS scripts in collaboration with JSC.


The following is an overview. The yellow background category belongs to the page resolution category, and the red background section belongs to the execution category.

* The code of the main classes is basically concentrated in the bindings/JS directory.

2.2 execution of JS Elements

The execution here does not include the page-based JS execution policies, mainly for specific execution processes.

 JsmainthreadexecstateConnects to the JSC module to execute JS scripts. In the system, it is the object of a single instance, that is, to ensure the single process and JSC cooperation. This is also a restriction of Js.

ScriptcontrollerMaintain an execution environment for javascriptcore and call jsmainthreadexecstate for execution if necessary.

 ScriptelementRepresents a specific script element, including JavaScript and SVG.


A sequence diagram is attached to help you understand the relationship between them (the script execution decision is initiated by htmlscriptrunner ):

2.3 parsing and Management of JS Elements

In WebKit, page parsing and script control operations are mainly implemented in htmldocumentparser, htmlscriptrunner, and scriptelement.


2.3.1 JS Parsing

Starting from the classic image below:

This figure is from the W3C official definition. It is related to the main text that JS causes page parsing blocking because it allows the script to use document. write () changes the page content, and the DOM tree may need to be re-parsed (reparser ). Therefore, JavaScript developers should pay attention to JS implementation methods, such as writing non-block
Script.


In addition, not only JS blocks parser, but style sheet also blocks Js. If JavaScript contains a display attribute check for an element, no correct result will be returned if CSS has not been loaded and parsed. Therefore, different definitions are also available in WebKit.


There are two important member variables in htmlscriptrunner:

M_scriptstoexecuteafterparsing-> Added by requestdeferredscript.

M_parserblockingscript
-> Added by requestparsingblockingscript.


According to the name, it can be seen that the former is to save the defer script, and the latter is to save the General script. Async is triggered after the download is complete.

2.4 JS running Policy

Previously, the execution methods for loading different JS attributes will be different:

Async-> is executed by scriptrunner: policyscriptready when the script download is complete.

Defer-> is executed when htmldocumentparser: policyfinished () is parsed on the page.

Other JS scripts are detected and executed by htmldocumentparser: cantakenexttoken during token processing.


2.4.1 General Javascript script execution

Generally, there is no JS script with the async and defer attributes. It is called the parsing blocking script (parsing blocking scripts), which is executed by htmlscriptrunner: executeparsingblockingscripts.



A typical Call method is as follows:

For example, when a new token is parsed, the document parser will trigger a cantakenexttoken to check the status. One of them is to check whether the script can be run. If the conditions are appropriate, the corresponding script will be executed. The so-called conditions are suitable. You can see them in the htmlscriptrunner: ispendingscriptready that it will call (the function is also easy to understand, that is, whether the previously suspended script can be executed again ):

bool HTMLScriptRunner::isPendingScriptReady(const PendingScript& script){    m_hasScriptsWaitingForStylesheets = !m_document->haveStylesheetsLoaded();    if (m_hasScriptsWaitingForStylesheets)        return false;    if (script.cachedScript() && !script.cachedScript()->isLoaded())        return false;    return true;}


Two conditions are waiting:

1. Is CSS being loaded.

2. Is the script trustworthy? The script is still being loaded.


Next we will introduce an entry. Some scripts are executed only after the CSS is loaded. Therefore, the calling process is as follows:


2.4.2 async and defer Script Execution

The following two figures are attached to illustrate the implementation process of the two. Some unimportant steps are omitted in the middle.


The execution process of async is triggered by resource loading:



In addition to the execution process of the defer script, there are also some exception considerations, such as processing during htmlscriptrunner analysis.

2.4.3 further reading of code guidelines

Taking htmlscriptrunner's runscript as an example, it is called by htmlscriptrunner: Execute (), which corresponds to the W3C standard process: Running
A script:



This part involves a lot of details, you can refer to W3C definition to further read the code.

Http://www.whatwg.org/specs/web-apps/current-work/multipage/scripting-1.html

Scriptelement: preparescript ()-> http://dev.w3.org/html5/spec/Overview.html#prepare-a-script


WebKit also marks the corresponding standard document chapter in important functions. You can read this section before reading the code.



Take a note and try again later.


Reprinted please indicate the source: http://blog.csdn.net/horkychen

Reference: WebKit Research

You can download the related UML diagram here: WebKit documentation on GitHub

Series indexes:

Basics (1) JSC and WebCore

Basics (ii) interpreter basics and JSC Core Components

Basic (3) code implementation from script code to JIT compilation

Basic (4) page parsing and JavaScript element execution

Advanced Article (1) SSA (Static Single Assignment)

Advanced (ii) type inference)

Advanced (iii) register allocation & trampoline

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.