High-Performance Ajax

Source: Internet
Author: User
Tags script tag browser cache

XMLHttpRequestjavascript

High-performance Ajax should consider data transfer techniques and data formats, as well as other optimization techniques such as data caching.

First, request data

The commonly used techniques for requesting data are XHR, dynamic script injection, Multipart XHR, IFRAMEs, Comet Five, of which the first three are more common, and the latter two are often used in more extreme situations.

1, XMLHttpRequest

This is the preferred technique, there are two ways, post and get,
Get: For requests that do not change the state of the server, only get the data, the data from theGET request is cached and can help improve performance for situations that require multiple requests for the same data.
Disadvantage: The requested URL plus the parameter length close to or more than 2048 characters, will cause the URL is truncated (in IE, ie limit url length, ie the limit of URL length is 2083 bytes (2k+35). For other browsers, such as Netscape, Firefox, etc., there is theoretically no length limit, and its limitations depend on the support of the operating system. ), you need to use post.
Post: There is no theoretical post limit and can be used for a large amount of data transfer.
Note: When you request data through XHR, you cannot access the data

2. Dynamic Script Injection

Overcomes the limitations of XHR: Ability to request data across domains
By creating a script tag, point src to a different domain URL.
Compared to XHR:
(1) Dynamic script injection Cannot set header information,
(2) can only use the Get method, cannot use the Post method,
(3) The requested header information cannot be accessed, and the response message cannot be processed as a string, and the response message is typically an executable JavaScript script (other XML, JSON, or other formatted data to be returned is encapsulated in a callback function)

3, Multipart XHR

MXHR allows clients to transfer multiple resources from the server side to the client with only one HTTP request. It is sent to the client by wrapping multiple resources (CSS files, HTML fragments, JS code, base64 encoded pictures) on the server side into a long string separated by a specific character as agreed by both parties. Then, the client parses the long string into individual resources based on that particular character.
For example:

  1. $dataArr=array();
  2. $images=array(‘1.jpg‘,‘2.jpg‘,‘3.jpg‘);
  3. foreach($images as $img){
  4. $file=fopen($img,‘r‘);
  5. $imgdata=fread($file,filesize($img));
  6. $imgdata=base64_encode($imgdata);
  7. fclose($file);
  8. array_push($dataArr,$imgdata);
  9. }
  10. $newchar=chr(1);
  11. echo implode($newchar,$dataArr);//使用一个不会出现在base64中的一个字符将各个图片的base64编码连成一个长字符串

After the data arrives at the client, it is parsed

  1. function splitImage(imgstring){
  2. var imgdata=imgstring.split(\u0001‘); //将字符串分割
  3. var img=document.createElement(‘img‘);
  4. for(var i=0,len=imgdata.length;i<len;i++){
  5. var tmpimg=img.cloneNode();
  6. tmpimg.src="data:image/jpeg;base64,"+imgdata[i];
  7. document.getElementById(‘div1‘).appendChild(tmpimg);
  8. }
  9. }

Because there are many resources in a one-time request, it is not necessary to wait for all resources to be returned for processing, the response status can be monitored according to the readystate status value, and when readystate is 3 o'clock, the portion of the data received is processed.
Pros: Multiple resources can be requested at a time to improve performance
Disadvantage: The retrieved resource cannot be cached by the browser (to return the resource as a string)
IE7 The following version does not support the status of ReadyState to 3

Second, send data 1, XHR

The Get mode is limited by the browser's maximum URL size, and when the amount of uploaded data is large, post.
For a small amount of data, the Get method is faster because a GET request sends only one packet to the server, while a POST request sends at least two packets, a Mount header information, a load
Post body.

2. Beacons Beacon

Beacons, like dynamic script injection, first creates an image object that points to the URL of the script on the server that contains the key-value pairs that are uploaded to the server by means of get.

  1. var params=["namme=lc","id=1"];
  2. var url="/test.php";
  3. var beacons=new Image();
  4. beacons.src=url+"?"+params.join("&");
  5. //注:并没有将它插入DOM中 所以图片是不显示的

After the server receives the data, there is no need to return the feedback information to the client. However, you can also make different responses on the server, such as a blank image that returns 1px wide represents a successful reception, and a 2px wide blank image represents a failed receive.

  1. beacons.onload=function (){
  2. if(this.width==1){
  3. //成功
  4. }else if(this.width==2){
  5. //失败
  6. }
  7. }

Using beacons is the quickest and most efficient way to send data back to the server, and the server does not need to return any response bodies.
Cons: Cannot use post, the amount of uploaded data is limited, the server response type is very limited.
So, if you want to return a lot of data to the client, you can only use XHR
If you only care about sending data to the server (you may want to return a small amount of information), you can use a picture beacon.

The Beacons method is ingenious, such as it can take advantage of the image object's Src property, the browser creates a new Image object will load its SRC attribute value, if we want to pass to the server parameters using & connected to form the URL of the Get method, and then assigned to SRC, Then the browser can send the parameters we want to pass to the server when the request is made. We can make a different response on the server, such as the return 1px wide blank image for the successful reception, 2px wide blank image represents the failure to receive. This method of passing data is typically used to count requests that are not required to be completed, such as user behavior.

Add:
The security of post is higher than the security of get. Note: The security described here is not the same concept as the "security" mentioned in get above. The meaning of "security" above is simply not to make data changes, and the meaning of security here is the meaning of true security, such as: submit data through get, user name and password will appear in plaintext on the URL, because (1) the login page may be cached by the browser, (2) Other people to view the browser's history, Then other people can get your account number and password, in addition, using get to submit data may also cause Cross-site request forgery attack. Reference: http://www.cnblogs.com/hyddd/archive/2009/03/31/1426026.html

3. Data format

When the server side and the client data transfer, the format of the data will affect its download speed and resolution speed, in general, JSON form and character-delimited custom format is the best. XML, HTML generally increase the amount of data, parsing slower.
If you have large data volumes and require parsing time, you can choose:
A, json-p data, using dynamic scripting to get the data as a JS script run instead of string, parsing speed is very fast, can be used across domains, sensitive data should not be used
b, custom data, with XHR or dynamic script injection acquisition, through split resolution, slightly faster than json-p

4. Data caching technology

One is, on the server side, set the HTTP header information, using the browser cache
One is to store the acquired information locally on the client side, avoiding the request again
Set HTTP header information

    1. $lifetime=7*24*60*60;
    2. header(‘Expires‘.gmdate(‘D,d M Y H:i:s‘,time()+$lifetime).‘GMT‘);

Client implementations:
Save the response information to a local object

High-Performance Ajax

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.