Detailed description of Javascript loading and execution, detailed description of javascript Loading

Source: Internet
Author: User

Detailed description of Javascript loading and execution, detailed description of javascript Loading

First, let me talk about loading and executing Javascript. Generally, the browser has two major features for Javascript Execution: 1) execute Javascript immediately after loading; 2) during execution, subsequent content on the page will be blocked (including page rendering and download of other resources ). Therefore, if multiple js files are introduced, these js files are serialized and executed in sequence in the browser.

Because javascript may operate the DOM tree of HTML documents, browsers generally do not download js files in parallel like parallel downloading css files, because this is caused by the particularity of js files. Therefore, if your javascript wants to operate the DOM elements behind it, basically, the browser will report an error saying that the object cannot be found. When Javascript is executed, the following HTML is blocked, and there is no DOM node in the DOM tree. So the program reports an error.

Traditional Method

Therefore, when you write the following code in the Code:

Copy codeThe Code is as follows:
<Script type = "text/javascript"
Src = "http://coolshell.cn/asyncjs/alert.js"> </script>

Basically, the <script> label in the head blocks subsequent resource loading and the generation of the entire page. I made a special example. You can see: Example 1. Note: In my alert. js, there is only one sentence: alert ("hello world"), which makes it easier for you to see how javascript blocks things behind it.

So, you know why many websites put javascript at the end of the web page, or use events such as window. onload or docmuemt ready.

In addition, because the vast majority of Javascript code does not need to wait for pages, we load the function asynchronously. So how can we load data asynchronously?

Document. write Method

Therefore, you may think that the document. write () method can solve the non-blocking method. Of course you will think that after the <script> label of document. write is executed, You can execute the following things. That's right. For Javascript code in the same script tag, this is the case, but for the whole page, this will still block. The following is a test code:

Copy codeThe Code is as follows:
<Script type = "text/javascript" language = "javascript">
Function loadjs (script_filename ){
Document. write ('<' + 'script language = "javascript" type = "text/javascript "');
Document. write ('src = "'+ script_filename +'"> ');
Document. write ('<' + '/script' +'> ');
Alert ("loadjs () exit ...");
}
Var script = 'HTTP: // coolshell.cn/asyncjs/alert.js ';
Loadjs (script );
Alert ("loadjs () finished! ");
</Script>
<Script type = "text/javascript" language = "javascript">
Alert ("another block ");
</Script>

What do you think is the order of alert? You can try it in different browsers. The test page to be closed: Example 2.

Defer and async attributes of the script

IE supports defer labels since IE6, such:

Copy codeThe Code is as follows:
<Script defer type = "text/javascript" src = "./alert. js">
</Script>

For IE, this label allows IE to download js files in parallel and hold the execution to the entire DOM load (DOMContentLoaded ), the <script> of multiple defer operations are also executed in the order they appear. The most important thing is that after <script> is added with defer, it will not block subsequent DOM rendering. However, this defer is only dedicated to IE, so it is generally used less.

Our standard HTML5 also adds the property of Asynchronously loading javascript: async, No matter what value you assign to it, as long as it appears, it starts to asynchronously load js files. However, async asynchronous loading has a serious problem, that is, it faithfully implements the military rule "execute immediately after loading". Therefore, although it does not block page rendering, however, you cannot control the execution order and timing. Let's take a look at this example.

Browsers that support async tags are: Firefox3.6 +, Chrome 8.0 +, Safari 5.0 +, IE 10 +, and Opera (from here), so this method is not very good. Because not all browsers can be used.

Dynamic DOM Creation

This method may be the most useful.

Copy codeThe Code is as follows:
Function loadjs (script_filename ){
Var script = 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 );
}
 
Var script = 'HTTP: // coolshell.cn/asyncjs/alert.js ';
Loadjs (script );

This method is almost a standard asynchronous loading of js files. for demonstration of this method, see Example 3. This method is also used to play out the JSONP stuff, that is, I can specify a background script (such as PHP) for the src of the script, and this PHP returns a javascript function, the parameter is a json string that returns to call our pre-defined javascript function. You can take a look at this example: t. js (this example is a small example of asynchronous ajax call I have collected on Weibo)

Load js asynchronously as needed

The preceding example of the DOM method solves the problem of loading Javascript asynchronously, but it does not solve the problem that we want him to run at the specified time. Therefore, we only need to bind the preceding DOM method to an event.

For example:

Bind to the window. load event -- Example 4

You must compare the differences between Example 4 and Example 3 in execution. I have used a javascript code highlighted in both examples, check the execution of the highlighted script and my alert. the execution of js is different)

Copy codeThe Code is as follows:
Window. load = loadjs ("http://coolshell.cn/asyncjs/alert.js ")

Bind to a specific event-Example 5

Copy codeThe Code is as follows:
<P style = "cursor: pointer" onclick = "LoadJS ()"> Click to load alert. js </p>

This example is simple. When you click a DOM element, it will actually load our alert. js.

More

However, binding to a specific event seems to be a bit more difficult, because it is too slow to download js only when you click it. Now, we want to throw our ultimate problem-we want to asynchronously download the js file to the user's local directory, but not execute it, only when we want to execute it.

It would be nice if we had the following method:

Copy codeThe Code is as follows:
Var script = document. createElement ("script ");
Script. noexecute = true;
Script. src = "alert. js ";
Document. body. appendChild (script );
 
// We can do this later
Script.exe cute ();

Unfortunately, this is just a beautiful dream. Today our Javascript is still primitive, and this "JS dream" has not been implemented yet.

Therefore, our programmers can only use the hack method.

Some programmers use non-standard script types to cache javascript. For example:

Copy codeThe Code is as follows:
<Script type = cache/script src = "./alert. js"> </script>

Because of "cache/script", this item cannot be parsed by the browser at all, so the browser cannot use alert. when javascript is executed, but he wants to download the js file again, you can do it. Unfortunately, webkit strictly follows the HTML standard-to delete something you don't know and do nothing about it. So our dream broke again.

Therefore, we need to hack it again. Just like playing With preload images many years ago, we can use the object tag (or the iframe tag), so we have the following code:

Copy codeThe Code is as follows:
Function cachejs (script_filename ){
Var cache = document. createElement ('object ');
Cache. data = script_filename;
Cache. id = "coolshell_script_cache_id ";
Cache. width = 0;
Cache. height = 0;
Document. body. appendChild (cache );
}

Then, let's call this function at the end. See example 6.

In Chrome, press Ctrl + Shit + I to switch to the network page. You can see that alert is downloaded. js is not executed, and then we use example 5. Because the browser has a cache, we will not download alert from the server. javaScript. Therefore, the execution speed can be ensured.

You should be familiar with this kind of preload. You can also use Ajax, such:

Copy codeThe Code is as follows:
Var xhr = new XMLHttpRequest ();
Xhr. open ('get', 'new. js ');
Xhr. send ('');

I will not talk about it here, nor give examples. You can try it on your own.

Finally, I will mention two more javascript codes, ControlJS and HeadJS, specifically used for asynchronous load javascript files.

Well, this is all the content. I hope you can understand the loading and execution of Javascript and related technologies. At the same time, I also hope that the front-end experts will not be enlightened!

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.