Advanced guidelines for high-performance website construction (III.)

Source: Internet
Author: User
Tags script tag

Fifth chapter integration of asynchronous scripts

1, the script if the normal load <SCRIPG src= "" ></script not only block the download of other content in the page, but also block the rendering of all elements behind the script, the asynchronous load script can avoid this blocking situation. However, when code executes asynchronously, there may be a race condition that results in an undefined identifier error. If inline scripting relies on external scripting, such as referencing jquery, it is important to ensure that the order is executed, and that the external script must be downloaded, parsed, and executed before the inline script.

2. Competitive status

There is no technology that can be downloaded in parallel while maintaining the order of execution, and the only exception is the script DOM Element executed in Firefox

3. Maintain execution order when loading scripts asynchronously

When an external script is loaded as usual, it blocks the execution of inline code, the race state does not occur, and if we start to load the script asynchronously, we need to integrate the inline code with the external script that relies on inline code, which is:

(1) hard-coded callback (hardcoded CallBack): Allows external code to invoke functions in the inline code, which is not flexible.

(2) window onload: To trigger the execution of inline code by listening to the OnLoad event of the window, there are two drawbacks: one is that the asynchronous script is loaded by blocking the OnLoad event, and the other is potentially causing the in-line code to delay execution.

(3) Timer: Use the polling method to ensure that the external scripts that are dependent on the code in the row are loaded, such as the SetTimeout () method.

(4) Script onload: is the best choice to resolve all problems by listening to the Onload event of the script.

(5) Degrading script tags--downgrade using the script tag, avoids the error of undefined identifier, the following code:

<script src= "Jquery.js" type= "Text/javascript" >
jquery (' P '). addclass ("pretty");
</script>

But some browsers do not support this syntax

4, previously said is to load a single script, if there are multiple scripts and in-line code to be executed in the order specified.

Sixth chapter layout in-line script

Inline scripting does not generate additional HTTP requests, but it blocks resources on the page and downloads, and blocks progressive rendering.

Solutions are:

(1) Move the in-line script to the bottom

(2) using asynchronous callback to start the execution of JS----simple asynchronous call technique is to use settimeout.

function Longcode () {
var vstart=number (new Date ());
while ((vstart+5000) >number (New Date ()))
{};
SetTimeout (vstart,0);
}

(3) Using script's defer attribute, no settimeout () is good.

(4) Keep CSS and JS in the execution order

Browsers apply their style sheets in the order they are listed in the page, regardless of the download order.

(5) Putting inline scripts behind stylesheets is risky: When the stylesheet is downloaded and the inline script finishes, the subsequent resources start downloading, and most downloads do not block inline scripting.

Solution: Adjust the position of the inline script so that it does not show up between the style sheet and any other resources. The inline script is placed before the style sheet.

The seventh chapter compiles the efficient JS

1. Management scopes

When JS is executed, JS creates an execution context, and the execution context sets the environment in which the code executes, and the JS engine creates a global execution context after the page loads, and then creates a corresponding execution context for each function, and finally builds a stack of execution contexts. The execution context currently in effect is at the top of the stack.

Each execution context has a scope chain associated with it, used to resolve identifiers, and the scope chain contains one or more variable objects that define the identifiers within the scope of the execution context. There is only one variable object in the scope chain of the global execution context, which defines all the available variables and functions on the JSK.

When the function is created, the JS engine assigns the scope of the creation execution context to the internal properties of the function, and when the function is executed, the JS engine creates an active object and assigns values to the this,arguments, named arguments, and all global variables of the function at initialization time.

The active object appears at the top of the scope chain of the execution context, immediately following the object in the function's properties.

The following code executes when executing context and scope chain relationships:

function Add (num1,num2) {
return num1+num2;
}
var result=add (5,10);

Console.log (result);

Local variables are the fastest read and write identifiers in JS, and the darker the identifiers are, the more slowly this phenomenon is found in almost all browsers. The higher the identifier's position in the scope chain, the faster it will be accessed.

Any non-local variable that is used more than once in a function should be stored as a local variable, such as this code:

function Creatforchild (ElementID)
{
var Elementr=document.getelementbyid (ElementID);
Newelement=document.createelement (' div ');
Elementr.appendchild (newelement);
}

Because document is used more than 1 times, it is stored as a local variable:

var doc=document;

The global variable object is always the last object in the scope, so parsing the global identifier is always the slowest.

Note: Ignoring the var keyword when assigning a variable for the first time can cause performance problems because the JS engine automatically creates a global variable when an undeclared variable is assigned a value.

During code execution, the scope chain corresponding to the execution context usually remains the same, but there are two statements that temporarily grow the scope chain of the execution context, which is the catch clause in the WITH statement and the Try...catch statement, but the effect of the catch clause is less than the WITH statement. However, be careful not to execute too much code in the catch clause to avoid performance impact.

PersonInfo ();
function PersonInfo () {
var person={name: ' Marry ', age:30};
With (person) {
document.write (name+ "is:" +age+ "years");
}
}

The WITH statement deepens the scope chain

Managing the scope chain is an easy way to raise high performance.

2. Efficient data access

There are four places in the script that can access data:

(1) Literal value

(2) Variables

(3) Array elements: by index

(4) Object properties: By property value

The overhead of accessing data from literal values and local variables is very small, and there is no need to worry about performance issues.

Time for each browser to access data:

function process (data)
{
if (data.count>0)
{
for (Var i=0;i<data.count;i++)
{
ProcessData (Data.items[i]);
}
}
}

Rewrite to local variable access time will be shortened

function process (data)
{

var Count=data.count;
if (count>0)
{
for (Var i=0;i<count;i++)
{
ProcessData (Data.items[i]);
}
}
}

In data access, it is a good way to improve performance by storing variable attributes and data elements as local variables more than once.

For most browsers, there is little difference between taking a variable attribute with Data.count or Data[count].

Window.onload=function () {
var divs=document.getelementsbytagname (DIV);
for (Var i=0;i<divs.length;i++)
{
var div=divs[i];
Process (div);//Output div contents
}
}

Rewrite it so that the access speed is faster

Window.onload=function () {
var divs=document.getelementsbytagname ("div");
for (Var i=0;lens=divs.length;i<lens;i++)
{
var div=divs[i];
Process (div);//Output div contents
}
}

3. Flow control

(1) Quick condition judgment

Advanced guidelines for high-performance website construction (III.)

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.