"Front-end Foundation" Dynamic Scripting and JSONP

Source: Internet
Author: User
Tags script tag

Bo Master Entry two months, more and more feel the importance of playing a good foundation for front-end engineers, in the direction of the crazy drag cool frame & build tools before the mad, must have a solid foundation to hit the bottom, not easily overturned. So bloggers have recently been in the bad patch "JS advanced Programming", found a lot of the first time to read the neglected, interesting place. is a classic, often read new Ah!

Part 1 The most familiar stranger--dynamic scripting

For some people just contact the front end of the classmate, "dynamic script" may be a few unfamiliar words, I also accidentally look at the elevation, just think of you ... No, only to notice the technology. But in fact, this is the technology that every front end uses every day, and it's the basic technology that works from jquery to all sorts of cool front-end frameworks. Then who is it?

To see a line of code:

<src= "Jquery.js"></script>

Familiar, huh?

Did you write it?

Congratulations, you are already a front-end siege lion that will use dynamic scripting technology!

...... Nani?

That's right! Do not think this line of code is commonplace, in fact, carefully studied, but also quite a little because of the lack of boats it ~

Remember, the Web page is ultimately an HTML page, and there is nothing else . Other such as JS, CSS, pictures, etc., are the resources on the page, from the page belongs to. The JS code is added to the Web page only as the inner text of the DOM node of the script type, and is executed when the browser parses the DOM structure into the script node. Dynamic scripting, as the name implies, is "dynamic" JS code-"Dynamic" means that it is not written in advance on the HTML page, but in the process of page parsing was added.

There are two ways to add scripts dynamically: One is DOM operations, inserting a script node into a page like other types of DOM nodes, the inside of which the JS code will be executed immediately, and the second is to load the JS file onto the page from a path, as shown in the jquery example. It can be understood that the code in the file is copied and pasted into the script tag, which is executed after the load is completed.

Give me a chestnut:

<!--for brevity, write only the body code -<Body>    <!--Static Script -    <Script>Console.log (1); varScriptDom=Document.createelement ('Script'); Scriptdom.innerhtml= 'Console.log (2);'; //content of the dynamic scriptDocument.body.appendChild (scriptdom); //dynamically inserting a script DOM nodeConsole.log (3); </Script></Body>

There is a static script on this page that, when executed, inserts a script child node into the body. Open this page in a browser, the console will print out the "1 2 3" of the three numbers. Look at the page and turn it into this:

<!--for brevity, write only the body code -<Body>    <!--Static Script -    <Script>Console.log (1); varScriptDom=Document.createelement ('Script'); Scriptdom.innerhtml= 'Console.log (2);'; //content of the dynamic scriptDocument.body.appendChild (scriptdom); //dynamically inserting a script DOM nodeConsole.log (3); </Script>    <!--scripts that are inserted dynamically -    <Script>Console.log (2);</Script></Body>

The interesting part of this final page is the parcel "console.log (2);" The script tag is clearly in the back of the original label, but 2 is printed before 3. In fact, insert a dynamic script anywhere, where the code executes immediately after insertion. The same is true of the JS code introduced by the SRC attribute, which is executed immediately once the loading is complete.

It's a great expression of scripting language flexibility! Think of the compiled language, such as C + +, Java, all the code must be pre-compiled to execute, can not be done like JS, do not compile not to say, but also in the original code execution in half, suddenly inserted into a bunch of new code and immediately get executed; it's like the dinner party invited 99 guests, half the meal, Suddenly came an uninvited guest, or an unsolicited cooked, sat down began to laugh with the crowd, vodka flowed, so the host JavaScript conveniently on the number of guests changed to 100, no vainly disobey sense, if replaced by C + + or Java host, will only after the start of the party to all the entrance sealed dead, No one is allowed to enter.

Part 2 application of dynamic scripting: JSONP

Cross-domain is an almost necessary problem in front-end interviews, and Jsonp is a relatively simple solution.

The background of the birth of Jsonp is that "cross-domain" is only the security policy restrictions of Ajax, as long as the domain name , protocol , port These 3 items have 1 inconsistencies, the browser is forbidden to send AJAX requests. The SRC attribute of such a label such as <script><link> is not subject to this limitation, and can be filled in with the address of any domain name (think of the CDN address of jquery and a bunch of picture bed sites ...). )。 So smart front-end siege Lions think of the use of dynamic scripting to get JSON data routines, called json Padding, meaning "json fill."

What's the specific approach? In three steps

Step 1

Let the server side slightly change the code: when a GET request query parameter has callback one item, such as a URL length:

Http://someurl.com/data?callback=handler

Then the server does not directly take the JSON file as the response content, but instead returns a dynamically generated JS file, where the code is

Handler ({JSON data});

is actually a call to the handler function, and the JSON is "filled" in as a parameter.

Step 2

Back to the front. Define the handler function that is responsible for processing JSON data:

function Handler (JSON) {    //  processing JSON data }

Step 3

When you need to get data across domains, insert a script DOM element into the page:

var script= document.createelement (' script '= ' Http://someurl.com/data?callback=handler '; Document.body.appendChild (script);

The SRC attribute value of this script element comes with a callback query parameter, and the server returns the code in step 1, which is executed immediately after the download is completed, and handler happens to be a function that has already been defined. The desired cross-domain JSON data is then uploaded to the current page as a handler argument!

Finally, there are two things to note:

1. This method can request any type of data, not limited to JSON, just because JSON is most commonly used, so named Jsonp.

2. Jsonp is a technique used to help Ajax circumvent cross-domain limitations, which itself is not a half-dime relationship with Ajax and can be used with JSONP technology in browsers that do not support Ajax.

"Front-end Foundation" Dynamic Scripting and JSONP

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.