Loading and execution of "turn" JavaScript

Source: Internet
Author: User
Tags script tag

To undertake the previous article, "browser rendering principle introduction", This article to the next JavaScript loading and Execution.

In general, browsers have two main features for JavaScript operation:

1) execute immediately after loading

2) will block the subsequent content of the page (including rendering of the page, download of other resources) when executing

therefore, if more than one JS file is introduced, then for the browser, these JS files will be serially loaded and executed sequentially.

Since JavaScript may manipulate the DOM tree of HTML documents, browsers generally do not download the JS file in parallel with the parallel download of CSS files, which is caused by the particularity of the JS File. therefore, If your JavaScript wants to manipulate the DOM elements behind it, The browser will say that the object cannot be found because the HTML behind the JavaScript execution is blocked, and the DOM tree does not have a subsequent node when it is Manipulated.

Traditional way

When you write the following code:

<type= "text/javascript"  src= "http://coolshell.cn/asyncjs/ Alert.js "></script>

basically, the <script> tag in the head blocks the loading of subsequent resources and the creation of the entire page. For example above, there is only one sentence of JS code (example):

Alert ("hello world");

The effect is that when you load this JS file, a dialog box pops up, so clicking on this dialog box will not load the subsequent resources and generate the entire page.

so, There are a lot of websites will put JS on the last side of the page, or use window.load, $ (document), such as the Ready (function () {}) Events.

also, because the vast majority of JavaScript code does not need to wait for a page, we need to load the feature asynchronously. So how do we load it asynchronously?

Document.Write Way

You may think that the document.write () approach solves the non-blocking Approach. The Document.Write method can be used to write the <script> tag so that the following is done, for the JS code within the same script Tag. however, It is still blocked for the entire page. Here is a test code (example):

<Scripttype= "text/javascript"language= "javascript">    functionLoadjs (script_filename) {document.write ('<' + 'script language= "javascript" type= "text/javascript"'); document.write ('src= "' +Script_filename+ '">'); document.write ('<'+'/script'+'>'); Alert ("Loadjs () Exit ..."); }     varScript= 'Http://coolshell.cn/asyncjs/alert.js';    Loadjs (script); Alert ("Loadjs () finished!");</Script> <Scripttype= "text/javascript"language= "javascript">Alert ("another block");</Script>

The dialog box that pops up is:

Loadjs () Exit...loadjs () finished!hello worldanother block

The page is then Displayed.

Script's Defer and Async properties

ie since IE6 defer tags, such as:

<defer type= "text/javascript"  src= "./alert.js">< /script>

For ie, this tag will allow IE to download the JS file in parallel, and hold it to the entire DOM loading complete, the <script> of multiple defer will be executed in the order in which they appear to Run. The most important thing is that after the <script> is added refer, it does not block subsequent Dom Rendering. But because refer is only IE special, so the general use of relatively few.

Our HMTL 5 also adds an asynchronously loaded JavaScript attribute: async. No matter what value you assign to it, as long as it appears, it starts to load the JS file asynchronously. however, Async Asynchronous loading has a serious problem, that is, it faithfully executes the "load immediately after execution" Rule. so, while it does not block the rendering of the page, you cannot control the order and timing of his execution (example).

The browser that supports the async tag is as follows, Opera is not supported (from here), so this method is not too good.

How to create a DOM dynamically

This approach is probably the most used.

functionLoadjs (script_filename) {varScript = document.createelement (' script '); Script.setattribute (' Type ', ' Text/javascript '); Script.setattribute (' SRC ', script_filename); Script.setattribute (' ID ', ' coolshell_script_id '); script_id= document.getElementById (' coolshell_script_id '); if(script_id) {document.getelementsbytagname (' Head ') [0].removechild (script_id); } document.getelementsbytagname (' Head ') [0].appendchild (script);} varScript = ' Http://coolshell.cn/asyncjs/alert.js '; Loadjs (script);

This approach is almost the standard way to load a JS file asynchronously (example). This way also played out the JSONP. That is, we can specify a background script (such as php) for the src of the script, and this PHP returns a JavaScript function whose parameters are a JSON string that is returned to call our pre-defined JavaScript Function. Author's reference Example: T.js (this example is a small example of an asynchronous Ajax call that was previously solicited by the author on Weibo)

Asynchronous loading JS on demand

The above example of the DOM approach solves the problem of loading JavaScript asynchronously, but it doesn't solve the problem that we want him to run at the time I Specify. so, we need to bind the DOM method above to an Event.

Like what:

1) tied to the Window.load event (example)

Window.load = Loadjs ("http://coolshell.cn/asyncjs/alert.js")

2) tied to a specific event (example)

<style= "cursor:pointer"  onclick= "loadjs ()"> </ P >

For example, When we click on a DOM element, we load our JS File.

More

Some people may feel that the binding on a particular event seems to be a bit over, and the click on the load JS is too slow. Here is the ultimate problem: we want to asynchronously download the JS file to the user locally, but do not execute, only when we want to execute the time to Execute.

The author proposes a way to use the OBJECT tag (or the IFRAME Tag) as we did with the preload image years ago, so we have the following code (example):

function cachejs (script_filename) {    var cache = Document.createelement (' object ');     = script_filename;     = "coolshell_script_cache_id";     = 0;     = 0;    Document.body.appendChild (cache);}

Press F12 (or Ctrl+shit+i) under Chrome to switch to the network page, and you can see that the Alert.js file has been downloaded but does not perform the action that pops up the Hello,world dialog box. Then we use "tied to specific events" in the way, because the browser side has a cache, will not download the Alert.js file from the server, so that the execution speed can be Guaranteed.

We can also use Ajax methods, such as:

var New XMLHttpRequest (); xhr.open (' GET ', ' new.js '); xhr.send (');

finally, Two JS libraries, one is controljs, a called headjs, specifically used to do asynchronous load JavaScript files.

Source: JavaScript Loading and execution

Loading and execution of "turn" JavaScript

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.