Analysis based on JSONP principles (recommended) and analysis and recommendation of jsonp principles

Source: Internet
Author: User

Analysis based on JSONP principles (recommended) and analysis and recommendation of jsonp principles

Preface

The first project I have come into contact with since my work is the separation of the front and back ends. The front-end static files have their own independent domain names and use interfaces to obtain data for rendering and other operations.

Cross-origin methods do not need to be mentioned. You can search for them as needed. However, jsonp and CORS are the most commonly used methods. Jsonp focuses on the frontend, which is also a front-end Hack technique. CORS is more important than the backend, and the server needs to be configured in many places.

This article explains how jsonp works.

Basic Principles

The basic principle is easy to describe. Some tags on html pages are not subject to cross-origin restrictions, such as img, script, and link. If we put the data we need in a js file, then we can break through the same source browser restrictions.

Create a script tag

The dynamic script elements are mentioned in high-performance JavaScript, and the author writes:

1. The file starts to be downloaded when the element is added to the page. The focus of this technology is that the file download and execution process will not block other processes on the page at any time.

2. When a dynamic Script node is used to download a file, the returned code is usually executed immediately (except Firefox and Oprea, they will wait until all previous dynamic script nodes have been executed .) This mechanism works normally when the script is self-executed.

Reference 1 ensures that the main thread is not blocked during JSONP requests. Reference 2 ensures that the JSONP code will not encounter errors when it is automatically executed after the JSONP code is loaded.

Callback

After receiving a GET request, the server usually needs to determine whether the callback parameter exists. If yes, a method name and brackets must be added to the returned data. For example, initiate the following request:

http://www.a.com/getSomething?callback=jsonp0

The server returns the following content:

jsonp0({code:200,data:{}})

Obviously, because this is included in the Dynamically Loaded Script tag, this is a piece of Self-executed code. Only one function of this Code is called --- jsonp0.

Of course, if there is an execution, you must create it first; otherwise, an error will be reported. To create this step, you must execute it before the call.

The specific implementation is as follows:

Function jsonp (url, successCallback, errorCallback, completeCallback) {// declare the object. The function must be declared to the global scope window. jsonp0 = function (data) {successCallback (data); if (completeCallback) completeCallback () ;}// create a script tag and add the callback parameter var script = document after the url. createElement ('script'), url = url + (url. indexOf ('? ') =-1? '? ':' & ') + 'Callback = jsonp0'; script. src = url; document. head. parentNode. insertBefore (script, document. head); // After the script is loaded, it will be executed by itself}

The above basically completed the core of a jsonp method. At this time, jsonp0 is a declared function. If the server returns normally, jsonp0 will be executed, the successCallback callback is also executed.

Complete

In practice, many jsonp requests are usually called at the same time,

So since jsonp0 can meet our needs, why do we often see accumulated Code such as jsonp1 and jsonp2?

This is because the request may be asynchronous. When the jsonp method is executed for the first time, window. jsonp0 is function A. In this case, the js file is loaded and the jsonp method is called again when the js file is not loaded. At this time, window. jsonp0 points to function B. The second callback will be executed after two js loads are completed.

Therefore, we need to make a difference in the callback name so that the accumulation can meet the needs.

Modify the Code:

Var jsonpCounter = 0; function jsonp (url, successCallback, errorCallback, completeCallback) {var jsId = 'jsonp' + jsonpCounter ++; // declares an object, you need to declare the function to the global scope window [jsId] = function (data) {successCallback (data); if (completeCallback) completeCallback (); clean ();} // create a script tag and add the callback parameter var script = document after the url. createElement ('script'), url = url + (url. indexOf ('? ') =-1? '? ':' & ') + 'Callback =' + jsId; script. src = url; document. head. parentNode. insertBefore (script, document. head); // After the script is loaded, it will execute it by itself. // After executing this method, many script labels will appear before the head, we need to manually delete them. Function clean () {script. parentNode. removeChild (script); window [jsId] = function (){};}}

After the accumulation and cleaning are added, another important thing to handle is the error callback. Normally, a timeout value is set when jsonp is requested. If the timeout value is exceeded, a timeout exception is thrown.

The implementation is as follows:

Var jsonpCounter = 0; function jsonp (url, successCallback, errorCallback, completeCallback, timeout) {// skip the code var timeout = timeout written above | 10000, timer; if (timeout) {timer = setTimeout (function () {if (errorCallback) {errorCallback (new Error ('timeout');} clean () ;}, timeout )} function clean () {script. parentNode. removeChild (script); window [jsId] = function () {}; if (timer) clearTimeout (timer );}}

In this way, all the functions of jsonp are basically completed, and some compatible modifications are required for the rest to be considered a complete jsonp method.

REFER

High-performance JavaScript

A jsonp implementation on npm,JSONP

The above analysis based on the JSONP principle (recommended) is all the content shared by the editor. I hope to give you a reference and support for the customer's house.

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.