JS program implementation and sequential implementation of the detailed __JS

Source: Internet
Author: User
Tags function definition

Statement: This is reproduced

Original post address: http://www.jb51.net/article/36755.htm

JavaScript is a descriptive scripting language, the browser for dynamic parsing and execution, browser for different ways have different analytic order, detailed described below, interested friends can refer to haDeclaration and invocation of functions
JavaScript is a descriptive scripting language that is dynamically parsed and executed by browsers. The function is defined in roughly the following two kinds, the browser for different ways have different parsing order.
The code is as follows:
Copy code code as follows:
Definition function definition
function Fn1 () {
Alert ("Hello world!");
}
An assignment function definition
var Fn2 = function () {
Alert ("Hello wild!");
}

During page loading, the browser scans each JS block (or file) on the page or load. If a defined function is encountered, preprocessing (similar to C, etc.) is done, and the processing is completed before starting from top to bottom, and when an assignment function is encountered, the function is only assigned to a variable without preprocessing ( Similar to the principle that a variable in 1 must be first defined and then processed before it is called. Here's a simple example:
The code is as follows:
Copy code code as follows:
Definition function definition
Fn1 ();
function Fn1 () {
Alert ("Hello world!");
}

Normal execution, pop-up "Hello world!", the browser to Fn1 preprocessing, and then from Fn1 (), start execution.
The code is as follows:
Copy code code as follows:
An assignment function definition
Fn2 ();
var Fn2 = function () {
Alert ("Hello wild!");
}

Firebug Error: FN2 is not a function, the browser did not preprocess the FN2, the sequence executes, so the error Fn2 undefined.

3. code block and JS file processing
"code block" refers to a pair of <script type= "text/web Effects" ></script> tags wrapped in the JS code, file refers to the file, nonsense: D
The browser scans each block or file independently, and then executes the global code sequentially (as mentioned in 2). So, in a block (file), a function can be defined "defined" after the call, but in two blocks, the block in which the function is defined must precede the block in which the function is called.
Very round the mouth, see examples of good:
The code is as follows:
Copy code code as follows:
<script type= "Text/javascript" >
Fn ();
</script>
<script type= "Text/javascript" >
function Fn () {
Alert ("Hello world!");
}
</script>
Error: Fn is notdefined, two blocks in exchange.

4. The duplicate definition function overrides the previous definition
This is the same as the duplicate definition of a variable, code:
The code is as follows:
Copy code code as follows:
function fn () {
Alert (1);
}
function fn () {
Alert (2);
}
FN ();
Pop-up: "2"

If so:
The code is as follows:
Copy code code as follows:
FN ();
function fn () {
Alert (1);
}
function fn () {
Alert (2);
}
Or pop-up: "2"

Or pop-up "2", why. 2 said it all.

5. The onload function of the body and the execution of the function inside the body
The function inside the body is executed before the OnLoad function to test the code:
The code is as follows:
Copy code code as follows:
HTML head ...
<script type= "Text/javascript" >
function Fnonload () {
Alert ("I am outside the wall!");
}
</script>
<body onload= "Fnonload ();" >
<script type= "Text/javascript" >
Alert ("I am inside the Wall.");
</script>
</body>
First eject "I am inside the Wall";
Then pops up "I am outside the wall!"

The body of the OnLoad event trigger condition is the body content loading completed, and the body of the JS code in this event before the trigger run (why? 6 tell you ...)

6. JavaScript is multi-threaded or single-threaded.
Strictly speaking, JavaScript is not a multithreaded concept, all programs are "single-threaded" sequential execution.
To cite a less-than-appropriate example:
The code is as follows:
Copy code code as follows:
function fn1 () {
var sum = 0;
for (var ind=0; ind<1000; ind++) {
SUM + + ind;
}
Alert ("The answer is" +sum);
}
function fn2 () {
Alert ("I know, I just don't say");
}
FN1 ();
FN2 ();

First eject: "The answer is 499500",
After the pop-up: "I know, I just don't say."

Then you must ask: that delay execution, Ajax asynchronous loading, not multithreading it. Yes, the following programs do look like "multithreading":
The code is as follows:
Copy code code as follows:
function fn1 () {
settimeout (function () {
Alert ("I call first")
},1000);
}
function fn2 () {
Alert ("I call after");
}
FN1 ();
FN2 ();
First eject: "I call after",
1 seconds to eject: "I call first"

It looks like the fn2 () and the delay program are going to go in two separate processes, but actually, this is the "callback" mechanism in JavaScript that works, like "interrupts and responses" in the operating system--The delay program sets an "interrupt", and then executes FN2 () for 1000 milliseconds, Then callback execution fn1 ().
Similarly, 5 of the body of the OnLoad event called function, but also using the callback mechanism--body after loading completed, callback execution Fnonload () function.
The data processing function in the AJAX request is the same.
A more in-depth discussion of JavaScript threading issues, see the threads in this JavaScript I see, and a brief introduction to JavaScript multithreaded programming on INFOQ.
Sleepy, say the callback function again.

7. Callback function
What is the callback function for? is the function of callback execution, and nonsense: D
As 6 said, the most common callback is the onclick, Onmouseo Tutorial ver, onmousedown, onload and so on browser event invocation function, as well as Ajax asynchronous request data processing function; settimeout delay execution, SetInterval loops execute functions, and so on.
Let's simply write a pure callback function to play:
The code is as follows:
Copy code code as follows:
function Onback (num) {
Alert ("Shanshan I am Late");
Execute num Slap
}
function dating (hours, callBack) {
var sp= 0; SP, Rage value
The female pig feet stood hours for an hour in the snow.
Loop start ...
SP + +;
Loop End ...
CallBack (SP);
}
Dating (1, onback);


two browser loading rendering Web page process parsing

The working mechanism of the browser, in a nutshell, is the process of communication between the Web browser and the Web server through the HTTP protocol. Therefore, the C/s handshake between the agreement is the HTTP protocol. The approximate process before the browser is received and started rendering is as follows:


From the browser address bar to start the request link, the browser through DNS resolution of the Domain name Mapping IP address, after the successful browser to the IP address to obtain a connection, the successful connection, the browser end of the request header information through the HTTP protocol to this IP address server to launch the request, The server waits for processing after receiving the request, and finally sends back the response to the browser end, at which point the browser receives the text/html type of code from the server under the HTTP protocol, the browser starts to display the HTML and gets the embedded resource address, and then the browser initiates the request to obtain the resources. and is displayed in the browser's HTML.

The tool that is closest to us and can directly display a complete communication process is firebug, look at the following figure:


The yellow tips floating layer tells us "colorbox.html" from initiating requests to shutting down the entire process of the duration (domain name resolution-> Establish a connection-> initiate a request-> wait for response-> receive data), click on the request, You can obtain HTTP headers information, including response header information and request header information, such as:

Response header Information http/1.1 304 not Modified date:wed, Mar 08:20:06 GMT server:apache/2.2.4 (Win32) php/5.2.1 connection:k Eep-alive keep-alive:timeout=5, max=100 Etag: "1e483-1324-a86f5621"
Request header information get/docs/eva/api/colorbox.html http/1.1 Host:ued.com user-agent:mozilla/5.0 (Windows; U Windows NT 6.1; ZH-CN; rv:1.9.2.13) gecko/20101203 firefox/3.6.13 accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 accept-language:zh-cn,zh;q=0.5 accept-encoding:gzip,deflate accept-charset:gb2312,utf-8;q=0.7,*;q=0.7 Keep-Alive: Connection:keep-alive Referer:http://ued.com/docs/if-modified-since:thu, Feb 10:14:07 GMT If-None-Match: " 1e483-1324-a86f5621 "Cache-control:max-age=0

In addition, Ajax asynchronous requests follow the HTTP protocol in a similar way.

Browser loads the order in which HTML page content is displayed

We often see the browser loading a page, some of the content first displayed, and some content after the display. So how does the browser load display HTML in what order?

In fact, the order in which browsers load display HTML is in the following order:
1, IE download the order is from top to bottom, the order of rendering is also from top to bottom, download and rendering is carried out at the same time.
2, when rendering to a part of the page, all the parts of it have been downloaded (not that all the associated elements have been downloaded).
3, if the semantic interpretation of the tag embedded file (JS script, CSS Sword  hit the pirate e download process will enable a separate connection to download.
4, and in the download after parsing, parsing process, stop the page all down elements of the download.
5. After the download completes, the style sheet is parsed with all previously downloaded style sheets, and after parsing is completed, all previous elements (including previously rendered) are rendered again.
6, JS, CSS, if there is a redefinition, after the definition function will overwrite the function defined before.

Firefox handles downloads and render sequences in roughly the same order, only slightly different in nuance, such as: IFrame rendering

If your page is larger, you want some content to show up first, stick to the viewer, then you can follow the rules of the above reasonable layout of your Web page, to achieve the intended purpose.

the load of JS
Cannot download and analyze in parallel (blocking downloads)
When JS is referenced, the browser sends 1 jsrequest and waits for the request to return. Because browsers need 1 stable DOM tree structure, and JS is very likely to have code directly changes the DOM tree structure, such as using document.write or appendchild, Even the direct use of the location.href to jump, the browser to prevent the occurrence of JS to modify the DOM tree, the need to rebuild the DOM tree, so it will block other downloads and rendering.

To get a clearer picture of the loading order of the page elements, write a program that delays 10 seconds for each element in the page.

The location of the program is shown in the attachment.

First look at the testhtmlorder.aspx page and use Httpwatcher to detect the loading of page elements.

You can see the loading order from the figure below.

IE first loaded the homepage face testhtmlorder.aspx,

After downloading the home page, the page first shows the "Red Sword", "Blue sword" several words, but at this point is only black font, no style, because the style has not been downloaded.

The next tab in the page is the JS tag, which is embedded in the file, so IE needs to download it. There are two files, although IE can establish two links with webserver, but at this time not using two connections, but using a connection, after the download is complete, then download another file.

The reason is because JS contains a syntax definition, in the second file inside the function may use the first file inside the variables and functions, ie no way to judge, or need a very time-consuming judgment, to determine the sequence of file downloads. And in terms of interpretation, ie to JS file is to download one, explain one (can execute file testjsorder2.aspx). If the second file is downloaded first, an explanation error occurs. Therefore, developers need to place their own JS file location, according to the order of precedence, ie in turn to download to explain. The following function overrides the previous function definition

After the download is complete, we see the helloworld,helloworld2 and start the sequential execution. The style sheet and picture of the font are still not downloaded.

At this point, the page stays at the interrupt point (alert part) where the function executes when helloworld,helloworld2 executes the procedure. At this point IE did not download the CSS file. This shows that the implementation of JS function will block ie download.

Next we see the CSS file download is also using a connection, but also a serial download. The reason for its serial download and JS serial download reason is the same.

In the two CSS file download process, we saw the "Red Sword", "Blue sword" turn into red and blue, the color of the conversion time difference in 10 seconds, indicating that the style file and JS file is the same download after a parse one.

Now turn to testcssorder.aspx, and you can see the "Red Sword Spirit" at the beginning, "Red strong sword, shown as red, after 10 seconds" Blue Sword "display for blue, after 10 seconds," Red Strong sword "font became thicker, and" red Strong Jian Ling 2 "began to appear. At the beginning of the "Red Sword Spirit", "Red Strong sword Spirit" when the red is displayed, the third style has not yet been downloaded, while IE uses the elements that have been downloaded to the style to render the above, while the "Red Sword Spirit", "Red Strong sword" style is defined differently, but the display effect is the same. After the third file is downloaded, ie again to "strong red sword" rendering again, at this time it becomes bold, all the above file loading and rendering finished, start rendering the following label "Strong Red Sword 2"

There is a need to prove: when IE use style to render the label, is not stopped the other page elements of the download? I would like to detect by adding longer rendering time (using filters to increase the number of tag elements), but no validation succeeded. Only from the implementation of the JS function inference CSS rendering is also so.

Next see is the picture file download, at this time see is two pictures at the same time start downloading, and is the download complete, immediately on the page began to show, until all the pictures download complete.

Note: The method by which a test file spends its time on a network transmission.

First of all, we need to understand the significance of the W AIT value in the detection: wait = The time spent by the server + network time

The time spent on the server we can use Thread.Sleep (10000); Let it rest 10s,

Like this:

This can probably be calculated 10.002-10 = 0.002 seconds, which is about the time spent on the network.

Source: Browser Load render Web page process parsing


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.