What is the cross-origin Ajax solution? Synchronous and asynchronous

Source: Internet
Author: User
Tags script tag

1. What are the status messages of the HTTP protocol?

1 **: request received, continue processing
2 **: The operation is successfully received, analyzed, and accepted.
3 **: the request must be further processed.
4 **: The request contains an error syntax or cannot be completed
5 **: the server failed to execute a fully valid request.

 

 

 

2. What is the cross-origin Ajax solution?

 

1. Document. Domain + IFRAME settings

 

For examples with the same primary domain and different subdomains, you can set document. domain. The specific method is to create an iframe in the a.html file after document. Domain = a.comthen, to control the contentdocument of IFRAME, so that the two JS files can interact with each other. Of course, this method can only solve the problem where the primary domain is the same but the second-level domain name is different. If you set the domian of script.a.com to alibaba.com in a whimsical manner, it will obviously report an error! The Code is as follows:

 

A.html on www.a.com

 

Document. Domain = 'a. com ';
VaR IFR = Document. createelement ('iframe ');
IFR. src = 'HTTP: // script.a.com/ B .html ';
IFR. style. Display = 'none ';
Document. Body. appendchild (IFR );
IFR. onload = function (){
VaR Doc = IFR. contentdocument | ifr.content##doc ument;
// Operate B .html here
Alert (Doc. getelementsbytagname ("h1") [0]. childnodes [0]. nodevalue );
};

B .html on script.a.com

Document. Domain = 'a. com ';

 

This method applies to communication between any pages in {www.kuqin.com, kuqin.com, script.kuqin.com, and css.kuqin.com.

 

Note: The domain of a page is equal to window. Location. hostname by default. The primary domain name is a domain name without WWW, such as a.com. The primary domain name is usually prefixed with a second-level domain name or multi-level domain name. For example, www.a.com is actually a second-level domain name. Domain can only be set as the primary domain name. You cannot set domain to c.a.com in B .a.com.

 

Problem:
1. Security: When a site (B .a.com) is attacked, another site (c.a.com) will cause a security vulnerability.
2. If multiple IFRAME is introduced to a page, you must set the same domain to operate all IFRAME operations.

 

2. dynamically create scripts

 

Although the browser is disabled by defaultCross-OriginBut it does not prohibit reference JS files of other domains in the page, and can freely execute the function (including operating cookies, Dom, and so on) in the introduced JS files ). Based on this, you can easily create a script NodeCross-Origin. For specific practices, refer to the Yui get Utility

 

It is quite interesting to judge whether the Script node is loaded: IE can only use the readystatechange attribute of the script, and other browsers are the load events of the script. The following describes how to determine whether a script has been loaded.

 

JS. onload = Js. onreadystatechange = function (){
If (! This. readystate | this. readystate = 'loaded' | this. readystate = 'complete '){
// Callback is executed here
JS. onload = Js. onreadystatechange = NULL;
}
};

 

3. Use IFRAME and location. Hash

 

This method is relatively difficult, but it can solve completelyCross-OriginUnder the circumstances of the Step Replacement problem. The principle is to use location. Hash to transmit values. In URL: http://a.com # helloword # helloworld is location. Hash, changing the hash does not cause page refreshing, so you can use the hash value for data transmission, of course, the data capacity is limited. The cs1.html file under the hypothetical domain name a.comis used to transfer the digest page to cs2.html under the cnblogs.comdomain name. The hash value can be used for parameter transfer.

 

Cs2.htmlafter the request is received, the modified cs1.html hash value will be passed for data transmission (because the two pages are not in the same domain, ie and chrome cannot modify the parent. location. hash Value, so you need to use a proxy IFRAME under the.com domain name; Firefox can be modified ). Add a timer to cs1.html at the same time to judge whether the location. Hash Value has changed over a period of time. If there is any change, obtain the hash value. The Code is as follows:

 

First, the cs1.html file under a.com:

 

Function startrequest (){
VaR IFR = Document. createelement ('iframe ');
IFR. style. Display = 'none ';
IFR. src = 'HTTP: // www.cnblogs.com/lab/cscript/cs2.html#paramdo ';
Document. Body. appendchild (IFR );
}

Function checkhash (){
Try {
VaR DATA = location. Hash? Location. Hash. substring (1 ):'';
If (console. Log ){
Console. Log ('Now the data is '+ data );
}
} Catch (e ){};
}
Setinterval (checkhash, 2000 );

Cs2.html under cnblogs.comdomain Name:

// Simulate a simple parameter processing operation
Switch (location. Hash ){
Case '# paramdo ':
Callback ();
Break;
Case '# paramset ':
// Do something ......
Break;
}

Function callback (){
Try {
Parent. Location. Hash = 'somedata ';
} Catch (e ){
// The Security Mechanism of IE and chrome cannot be modified by parent. Location. Hash,
// Use the proxy IFRAME in an intermediate cnblogs domain
VaR ifrproxy = Document. createelement ('iframe ');
Ifrproxy. style. Display = 'none ';
Ifrproxy. src = 'HTTP: // a.com/test/cscript/cs3.html#somedata'; // note that the file is in the "a.com" Domain
Document. Body. appendchild (ifrproxy );
}
}

 

A.comdomain name cs3.html

 

// Because parent. Parent belongs to the same domain, you can change its location. Hash Value.
Parent. Parent. Location. Hash = self. Location. Hash. substring (1 );

 

Of course, this operation also has many disadvantages, such as direct data exposure to URLs, limited data capacity and types ......

 

4. Implementation of window. Name Cross-OriginData Transmission

 

The long column in this article is not easy to read. For details, see the implementation of window. NameCross-OriginData transmission.

 

5. Use HTML5 postmessage

 

One of the coolest new features in HTML5 is cross-document message transmission. The next-generation browsers will support this function: chrome 2.0 +, Internet Explorer 8.0 +, Firefox 3.0 +, opera 9.6 +, and Safari 4.0 +. Facebook has used this function to support real-time web-based message transmission using postmessage.

 

Otherwindow. postmessage (message, targetorigin );

 

Otherwindow: Reference to the window on the receiving information page. It can be the contentWindow attribute of IFRAME on the page, the return value of window. open, and the value obtained from window. frames through name or subscript.
Message: The data to be sent, of the string type.
Targetorigin: used to restrict otherwindow. * indicates no restriction.

 

A.com/index.html code:

 

IFRAME id = "IFR" src = "B .com/index.html"/iframe
Script Type = "text/JavaScript"
Window. onload = function (){
VaR IFR = Document. getelementbyid ('ifr ');
VaR targetorigin = 'HTTP: // B .com '; // The result is the same if 'HTTP: // B .com/c/proxy.html' is written.
// If it is written as 'HTTP: // c.com ', no postmessage will be executed.
IFR. contentWindow. postmessage ('I was there! ', Targetorigin );
};
/Script

 

B .com/index.html code:

 

Script Type = "text/JavaScript"
Window. addeventlistener ('message', function (event ){
// Determine the message source address through the origin attribute
If (event. Origin = 'HTTP: // a.com '){
Alert (event. data); // The "I was there! "
Alert (event. source); // reference the window object in a.com;index.html
// However, due to the same-origin policy, event. source cannot access the window object.
}
}, False );
/Script

 

6. use flash

 

This is the method we can see from yui3's Io components. For details, see http://developer.yahoo.com/yui/3/io /.
For more information, see Adobe Developer Connection.Cross-OriginProxy file specifications: Ross-Domain Policy file specifications and HTTP headers blacklist.

 

 

 

 

 

3. What is the difference between synchronization and Asynchronization?

 

I. synchronous loading and asynchronous loading

 

1. synchronous Loading

 

We usually use this synchronous Loading Mode:

 

<script src="http://yourdomain.com/script.js"></script> 

 

The synchronization mode, also known as blocking mode, will stop the browser from processing and subsequent parsing. Therefore, the subsequent file loading (image), rendering, and code execution are stopped. The reason why JavaScript needs to be executed synchronously is that JavaScript may have the act of outputting document content, modifying Dom, redirection, etc. By default, synchronous execution is safe. In the past, it was generally recommended to put <SCRIPT> at the end of the page </body>, so as to minimize this blocking behavior and display the page first.

 

Simply put, the loaded network timeline is a waterfall model, while the asynchronously loaded timeline is a concurrent model.

2. Common asynchronous loading (script Dom element)

(function() {
var s = document.createElement(‘script‘);
s.type = ‘text/javascript‘;
s.async = true;
s.src = ‘http://yourdomain.com/script.js‘;
var x = document.getElementsByTagName(‘script‘)[0];
x.parentNode.insertBefore(s, x);
})();

Asynchronous loading is also called non-blocking. the browser will continue to process subsequent pages while downloading and executing Js.

 

This method is to create a script element in the <SCRIPT> label on the page with JS and insert it into the document. In this way, JavaScript code is downloaded without blocking.

 

The async attribute is the newly added asynchronous support in HTML5. For more information, see the following description ).

 

This method is called the script Dom Element Method and does not require the same JavaScript source.

 

JavaScript code is wrapped in anonymous functions and executed immediately to protect the variable name from being exposed to external visibility. This is a common method, especially in JS libraries.

 

For example, Google Analytics and Google + badge both use this asynchronous loading code:
(function() {
var ga = document.createElement(‘script‘); ga.type = ‘text/javascript‘; ga.async = true;
ga.src = (‘https:‘ == document.location.protocol ? ‘https://ssl‘ : ‘http://www‘) + ‘.google-analytics.com/ga.js‘;
var s = document.getElementsByTagName(‘script‘)[0]; s.parentNode.insertBefore(ga, s);
})();
(Function ()
    {var po = document.createElement("script");
po.type = "text/javascript"; po.async = true;po.src = "https://apis.google.com/js/plusone.js";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(po, s);
})();
However, This loading method will prevent the onload event from being triggered before the load is executed.Currently, many page codes require additional rendering during onload, so initialization of some pages will still be blocked.  3. asynchronous loading during onload

 

(function() {
function async_load(){
var s = document.createElement(‘script‘);
s.type = ‘text/javascript‘;
s.async = true;
s.src = ‘http://yourdomain.com/script.js‘;
var x = document.getElementsByTagName(‘script‘)[0];
x.parentNode.insertBefore(s, x);
}
if (window.attachEvent)
window.attachEvent(‘onload‘, async_load);
else
window.addEventListener(‘load‘, async_load, false);
})();

 

This is similar to the previous method, but the key is that it does not start loading JS asynchronously immediately, but starts asynchronous loading only when onload is used. This solves the problem of blocking onload event triggering.

 

Supplement: Domcontentloaded and onload events

 

Domcontentloaded: The page (document) has been parsed and the DOM element on the page is available. However, the referenced images and subframes on the page may not be fully loaded yet.

 

Onload: all resources on the page are loaded (including images ). The loading progress of the browser is stopped at this moment.

 

The two time points divide the timeline loaded by the page into three stages.

4. Other asynchronous loading methods

Because Javascript Dynamic FeaturesThere are also many asynchronous loading methods:

 

  • Xhr eval
  • Xhr Injection
  • Script in IFRAME
  • Script defer
  • Document. Write script tag
  • Another method is to use setTimeout to delay 0 seconds and other methods.

 

Xhr eval: Get JS content through Ajax and run eval.

 

var xhrObj = getXHRObject(); 
xhrObj.onreadystatechange =
function() {
if ( xhrObj.readyState != 4 ) return;
eval(xhrObj.responseText);
};
xhrObj.open(‘GET‘, ‘A.js‘, true);
xhrObj.send(‘‘);

 

Script in iframE: Create and insert an IFRAME element to execute JS asynchronously.

 

var iframe = document.createElement(‘iframe‘); 
document.body.appendChild(iframe);
var doc = iframe.contentWindow.document;
doc.open().write(‘<body onload="insertJS()">‘);
doc.close();

 

Gmail mobile: The JS content in the page is commented out, so it will not be executed. When necessary, obtain the text content in the script element, remove the comment, and run eval.

 

<script type="text/javascript"> 
/*
var ...
*/
</script>

  

What is the cross-origin Ajax solution? Synchronous and asynchronous

Related Article

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.