Asynchronous loading: Controljs A module that allows a script to load faster

Source: Internet
Author: User
Tags add object execution html tags key variable browser cache client

Article Introduction: about the use of controljs and basic explanation.

There are altogether three articles about Controljs, this is the first part. Controljs is a module that lets the script load faster (a JavaScript module for making scripts load faster). The structure of the three articles is:

1. Async Loading
2. Delayed execution
3.overriding document.write
About the first part of the asynchronous loading, the key is to draw the page as HTML as soon as possible, and then use JavaScript to optimize, or to use JS further rendering. We have seen a lot of web pages, showing users a blank, just because of waiting for hundreds of KB of JS files to download, parse, execute, and these JS is used to draw the page displayed to the user to see the DOM elements.

In fact, the above situation is easy to understand – but the real improvement is much more difficult. Good hundreds of KB of JS must be dismantled and reorganized. The logic code that creates the Web Dom through JS must all be synthesized into the backend server to generate HTML. Even with the latest server-side JS to achieve, is a very large refactoring project.

I went back to opera's delayed Script execution option. Once this option is in effect, JS will be shelved (move aside), allowing the page to be rendered first. And this option is really good, and there is no web site because the option to open the page error. I've also been keeping in touch with vendors from other browsers to get them to do the same, and I desperately want developers to be able to use this option as quickly as possible.

In recent years, some Web accelerators (such as Aptimize, Strangeloop, Fastsoft, CloudFlare, Torbit, and the recent mod_pagespeed) have sprung up. They modify the HTML tags in the page to improve the performance of the page. From these patterns, I figured out a way to make it easier to change HTML tags than to delay the loading of the page rendering JS.

So Controljs was born!

Controlling Download and execution
Controljs's goal is to allow developers to better control the load of JS. The key is to realize the "load" atmosphere two steps: Download [DOWNLOAD] (that is, get content) and perform [execution] (include parsing). For better performance, these two steps are necessary to separate the controls.

In the eyes of programmers who are sensitive to Web page performance, how to control the downloading of scripts is a popular topic. When the script uses the normal way (that is, <script src= "" ...). , the script blocks downloads of other resources (slightly better in a new version of the browser) and blocks the rendering of the page (in all browsers). The technique of using asynchronous script loading (asynchronous script loading) alleviates this problem in a large program. I have mentioned several techniques for asynchronous loading in the even faster Web sites. Labjs and Headjs are the JS modules that provide asynchronous loading. Although their asynchronous technology solves the problem of blocking during the download phase of the script, it does not resolve what happens when the script executes.

Page rendering and new resource downloads are blocked during the script execution phase. In today's Web pages, more and more scripts are being blocked in the execution phase of the script, especially on mobile devices. In fact, the Gmail mobile device group takes into account the problem of script execution, which perfects the new async technique that downloads JavaScript wrapped in comments. This technique enables the separation of script execution and downloads. The script is downloaded to the client (in the browser's cache), but because it is a script annotation, it is not blocked during execution (because it is not performed). When a user uses related features, some scripts are required to remove the annotation symbol and then eval executes the code.

Stoyan Stefanov, an excellent performance optimization pioneer, recently released a blog post preloading JavaScript without execution. He downloads the script using image or object (depending on the browser). Assuming that these scripts can be slow to exist in the client, you can then insert scripts using the script tag. This is also the technology used in Controljs.

Controljs:how to use it
Using CONTROLJS involves three steps of modification

Modify Point #: Add Control.js

I think the most ironic thing about the use of script loading modules is that loading these asynchronous scripts to load a seed file blocks the page. So from the beginning I had to make sure that Controljs was going to be loaded asynchronously.

var cjsscript = document.createelement (' script ');
CJSSCRIPT.SRC = "Control.js";
var cjssib = document.getelementsbytagname (' script ') [0];
Cjssib.parentNode.insertBefore (Cjsscript, cjssib); modify dot-hop: script that modifies the chain
The next step is to change the label of all the outside chain script to Controljs form. The original script references the following

<script type= "Text/javascript" src= "Main.js" ><script>script element's type to "Text/cjs", src to "data-cjssrc", As follows:

<script type= "Text/cjs" data-cjssrc= "main.js" ><script> Modify point #3 Modify inline scripts
Most pages will have inline scripts. These scripts have dependencies: variables in inline scripts generally rely on scripts outside the chain, and vice versa. It is important to note that the order in which the introverted scripts and the external chain scripts are executed is warranted. Therefore, the inline script must change the value of the Type property

<script type= "Text/javascript" >
var name = GetName ();
<script> Modify "Text/javascript" to "Text/cjs" as follows:

<script type= "Text/cjs" >
var name = GetName ();
<script> That's OK! Follow-up a series of work to Controljs worry about it!

Controljs:how It works
Now the script won't block the page because the Type property has changed to a value that the browser cannot recognize. This also allows Controljs to use a High-performance method for better control of script loading. Let's take a look at how CONTROLJS works. Of course, you can also view the Control.js code for a more detailed understanding.

We all want to be able to start downloading the script as soon as possible. Because we use image or object to download the script, they do not block the page during the download phase. And they're not downloaded as a script, so they don't execute. Controljs first finds all the script's tags, and the type is "Text/cjs". If the script has a data-cjssrc, then image (ie and opera browsers) or object (other browsers) will be created dynamically according to their URLs. (You can check out the Stoyan ' s post for more details).

In general, CONTROLJS will enter the execution phase after window load time (or, of course, execute code immediately or a DOM element is loaded). Controljs will iterate through all the scripts for the second time, making sure they all appear correctly on the page. If the script is an inline script, then its code is executed. If the script is an outside chain script that is downloaded dynamically by image or object, it will be inserted into the page as a script tag, and its code will be parsed and executed. If image or object does not download the end, then after a brief interval (a short timeout), re-enter just the traversal process.

I will also discuss the features of document.write and skip the implementation phase in subsequent articles. In this article, we first look at a simple example of asynchronous loading.

Async Example
To better demonstrate the asynchronous loading scenario, I created a file with three scripts at the top of the file:

main.js– consumes 4 seconds to download
• A section of inline script uses a variable of main.js
page.js– consumes 2 seconds to download, using a variable of inline script
I've made page.js download time shorter than main.js, to confirm that these scripts can be executed in the correct order (although page.js downloads are faster). My colleagues also included inline scripts, because this is also true of many pages (such as Google Analytics), but many script loaders do not support the order in which inline scripts are executed.

Async without Controljs is a basic paradigm. It uses the most common way to load the script. You can take a look at the HTTP Waterfall Chart (using HttpWatch) below the IE8 as shown in the following figure. IE8 is better than IE6 and IE7-enables main.js and page.js to load in parallel. But all IE will block the download of the picture because of the script loading. So the images1-4 are delayed. In all browsers, page rendering will be blocked. As you can see in the illustration, the Main.js blocking render lasts up to 4 seconds (the green vertical bar indicates when the page starts rendering)

Async with Controljs demonstrates how controljs resolves a blocking problem caused by a script. Unlike the example above, scripts and pictures are loaded in parallel. At the same time, page rendering also begins immediately. If you present both pages in a browser, you will find that Controljs pages will be much faster. Of course, you also find that there are 3 more requests in the diagram below, one for control.js– this is the code used to load the script asynchronously. The other two requests were downloaded two times because of Main.js and page.js. The first time is to use image or Objcet download, the second is to use the script tag to add the page to execute the code. Because Main.js and page.js already exist in the browser cache, they do not need additional download time. Just a short cache read time (that is, the two fine blue lines).

The CONTROLJS Project
Controljs is an open source project under the Apache license. You can find control.js in Controljs Google code project. The discussion about it can be in Controljs Google Group. For the example mentioned above, put it on my site Controljs home Page. I've only tested it in most browsers, and if you're going to go into a large-scale product environment, do more detailed testing.

Only Part1
This is just the first part of Controljs. It seems to have solved all the problems at the moment. If we just need to load asynchronously, then some of the other technologies have actually been implemented. But my goal is not to let the script block the rendering of the page. We have to face a problem if we deal with document.write. Another aspect is the implementation of a mobile group similar to Gmail-the download script does not block page rendering at the same time in the runtime. We will analyze them in detail in the two posts below.



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.