Detailed JavaScript loading and execution _ basics

Source: Internet
Author: User
Tags script tag

First, I want to talk about the loading and execution of JavaScript. Generally speaking, the browser for JavaScript to run two major features: 1 load immediately after the execution, 2 will block the subsequent content of the page (including page rendering, other resources to download). So, if a number of JS files are introduced, then for browsers, these JS files are serially loaded, and sequentially executed.

Because JavaScript might be able to manipulate the DOM tree of HTML documents, browsers generally do not download JS files in parallel with CSS files, because this is the specificity of JS files. So if your JavaScript wants to manipulate the following DOM elements, basically, the browser will complain that the object cannot be found. Because JavaScript executes, the HTML behind is blocked, and the DOM tree does not have a DOM node behind it. So the program also complains.

The traditional way

So, when you write in code, write the following code:

Copy Code code as follows:

<script type= "Text/javascript"
Src= "Http://coolshell.cn/asyncjs/alert.js" ></script>

Basically, the <script> tags in the head block the subsequent loading of resources and the generation of the entire page. I have done an example that you can look at: example one. Note: There is only one sentence in my alert.js: alert ("Hello World"), which makes it easier for you to see how JavaScript blocks back things.

So, you know why a lot of sites put JavaScript at the end of the page, or use window.onload or docmuemt ready events.

Also, because the vast majority of JavaScript code does not need to wait for pages, we asynchronously load the functionality. So how do we load it asynchronously?

Document.Write Way

As a result, you may think that document.write () is a way to solve the problem of not blocking. You will of course feel that the document.write <script> tag will be able to execute after the thing goes, which is true. This is true for the JavaScript code in the same script tag, but for the entire page, this still blocks. Here is a section of the test code:

Copy Code code 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 the order of alert is? You can try it in a different browser. Here's the test page to turn off: Example two.

Defer and Async properties of script

IE has supported defer tags since IE6, such as:

Copy Code code as follows:

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

For IE, this tag will allow IE to download the JS file in parallel, and its execution hold to the entire DOM loaded (domcontentloaded), a number of defer in the execution of the <script> will also run in the order in which they appear. The most important thing is that when <script> is added defer, it does not block subsequent DOM rendering. But because this defer is only IE dedicated, so generally used relatively little.

Our standard HTML5 also adds a property that asynchronously loads javascript: async, no matter what value you assign to it, it starts to load the JS file asynchronously as soon as it appears. However, there is a serious problem with the asynchronous loading of async, which is that it faithfully implements the "load immediately execute" rule, so although it does not block the rendering of the page, you cannot control the order and timing of his execution. You can take a look at this example to feel.

Browsers that support async tags are: firefox3.6+,chrome 8.0+,safari 5.0+,ie 10+,opera is not yet supported (from here) so this method is not too good. Because not all browsers you can do.

Dynamically creating DOM methods

This is probably the most used way.

Copy Code code 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 approach is almost the standard asynchronous loading of JS files, the way the demo see: Example Three. This way is also played out of the JSONP, that is, I can specify a background script (such as PHP) for the script src, and this PHP returns a JavaScript function, whose argument is a JSON string, Returns a function that calls our predefined JavaScript. You can take a look at this example: t.js (This example is a small example of an asynchronous Ajax call I used to solicit from Weibo)

Asynchronously load JS on demand

The above Dom example solves the problem of asynchronously loading JavaScript, but does not solve the problem we want him to run at the time we specify. So we just need to tie that Dom way up to an event.

Like what:

Tied to the Window.load event--Example four

You have to compare example four and example three in the implementation of what is different, I have in both examples are specifically using a code highlighted JavaScript, to see the code highlighted the execution of the script and my alert.js execution, you know the difference.

Copy Code code as follows:

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

Tied to a specific event--example five

Copy Code code as follows:

<p style= "Cursor:pointer" onclick= "Loadjs ()" >click to load Alert.js </p>

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

More

However, binding on a particular event seems to be a bit too much, because it is only when you click to download JS, which is too slow. OK, here, to throw our ultimate problem-we want to asynchronously download the JS file to the user's local, but not execute it, only when we want to execute it.

It would be nice if we had the following way:

Copy Code code as follows:

var script = document.createelement ("script");
Script.noexecute = true;
SCRIPT.SRC = "Alert.js";
Document.body.appendChild (script);

We can do that in the back.
Script.execute ();

Unfortunately, this is just a beautiful dream, today our JavaScript is still relatively primitive, this "JS Dream" has not yet been achieved.

Therefore, our programmers can only use the hack way to engage.

Some programmers use a nonstandard script type to cache JavaScript. Such as:

Copy Code code as follows:

<script type=cache/script src= "./alert.js" ></script>

Because "Cache/script", this thing can not be browser parsing, so the browser can not be alert.js when JavaScript to perform, but he is going to download JS file, so you can be done. Unfortunately, the WebKit strict character from the HTML standard-for this kind of do not know, directly delete, do nothing. So, our dream is broken again.

So, we need to hack a little bit more, just like when we played preload pictures for years ago, we could use the OBJECT tag (and we could use the IFRAME tag), so we have the following code:

Copy Code code 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 we call this function at the end. Please refer to the relevant examples: example six

By pressing CTRL+SHIT+I under Chrome and switching to Network page, you can see that the alert.js has been downloaded but not executed, and then we'll use example five because the browser has a cache and no more downloads from the server alert.js. So, we can guarantee the speed of execution.

You should not be unfamiliar with this kind of preload thing. You can also use Ajax in the same way as:

Copy Code code as follows:

var xhr = new XMLHttpRequest ();
Xhr.open (' Get ', ' new.js ');
Xhr.send (");

Here I will not say more, also do not give examples, we can try to go.

Finally, two JS, one is Controljs, a call Headjs, specifically used to do asynchronous load JavaScript files.

OK, this is all the content, I hope you can see the JavaScript in the loading and execution, as well as the relevant techniques have an understanding. At the same time, also hope that the front end master generous enlighten!

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.