Non-blocking JavaScript scripting and extension knowledge

Source: Internet
Author: User

JavaScript tends to block some of the browser's processing processes, such as HTTP requests and interface refreshes, which are the most noticeable performance issues facing developers. Keeping JavaScript files short and limiting the number of HTTP requests is just the first step in creating a responsive Web application. The more features an application contains, the more JavaScript code is needed, and keeping the source short is not always an option. Although downloading a large JavaScript file produces only one HTTP request, it locks the browser for a large period of time. To avoid this, you need to incrementally add JavaScript to the page, in a way that doesn't block the browser. The secret of non-blocking scripting is that when the page finishes loading, the JavaScript source code is loaded. Technically, this means downloading the code after the window's Load event has been issued. There are three ways to achieve this effect. Jingle County wei Bearing hardware

Deferred script

HTML 4 defines an extended property for the <script> tag: defer. This defer property indicates that the script contained in the element is not intended to modify the DOM, so the code can be executed later. The Defer property is supported only by Internet Explorer 4 and Firefox 3.5 's later browsers and is not an ideal cross-browser solution. On other browsers, the defer property is ignored,<script> tags are handled by default (causing blocking). This approach is still a useful solution if the browser supports it. Examples are as follows:

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

A <script> tag with the defer attribute can be placed anywhere in the document. The corresponding JavaScript file will start the download when <script> is parsed, but the code will not be executed until the DOM loading is complete. (Before the OnLoad event handle is called). When a defer JavaScript file is downloaded, it does not block other browser processes, so these files can be downloaded in parallel with other resources on the page. Any <script> element with the defer attribute will not be executed until the DOM is loaded, both inline and external script files. The following example shows how the defer property affects script behavior:

      

The code pops up three dialog boxes during page processing. If the browser does not support the defer property, the order in which the dialog box pops up is "defer", "script", and "load". If the browser supports the Defer property, then the order of popup dialogs is "script", "defer" and "load". Note that the <script> element labeled defer is not running after the second, but is called before the OnLoad event handle is processed. If your target browser includes only internet Explorer and Firefox 3.5, then the defer script is really useful. If you need to support multiple browsers across domains, there is a more consistent way to implement them.

Dynamic scripting elements

The Document Object Model (DOM) allows you to dynamically create almost all of the document content of HTML using JavaScript. The root of this is that the,<script> element is no different from the other elements of the page: reference variables can be retrieved through the DOM and can be moved, deleted, or created from the document. A new <script> element can be created very easily through standard DOM functions:

  var script = document.createelement ("script");      Script.type = "Text/javascript";      SCRIPT.SRC = "File1.js";      Document.getelementsbytagname_r ("Head") [0].appendchild (script);

The new <script> element loads the file1.js source file. This file starts downloading immediately after the element is added to the page. The point of this technique is that no matter where the download is initiated, the download and operation of the file does not block other page processing processes. You can even put the code in the

When a file is downloaded using a dynamic script node, the returned code is usually executed immediately (except for Firefox and opera, they will wait until all the previous dynamic script nodes have been executed). This mechanism works fine when the script is a "self-running" type, but it can cause problems if the script contains only the interfaces that are called by other script calls on the page. In this case, you need to track the script download complete and prepare for the proper situation. You can use dynamic <script> node emit events to get information about them.

Firefox, Opera, Chorme and Safari will issue a load event after the <script> node is received. You can listen to this event to get the script ready for notification:

  var script = document.createelement ("script")      Script.type = "Text/javascript";      Firefox, Opera, Chrome, Safari            script.onload = function () {            alert ("Script loaded!");      };      SCRIPT.SRC = "File1.js";      document.getElementsByTagName ("Head") [0].appendchild (script);

Internet Explorer supports an alternative implementation, which emits a ReadyStateChange event. The <script> element has a ReadyState property whose value changes with the process of downloading an external file. There are five kinds of values for readyState:

    • "Uninitialized" default state
    • "Loading" Download start
    • "Loaded" Download complete
    • "Interactive" Download complete but not yet available
    • "Complete" all data is ready.

In the Microsoft documentation, the ReadyState values do not necessarily appear in all of the <script> elements ' lifecycles, but they do not indicate which values are always used. In practice, we are most interested in the "loaded" and "complete" states. Internet Explorer does not match the final state represented by these two readystate values, sometimes the <script> element gets "loader" but never "complete", but in other cases "complete" appears And not to use "loaded". The safest way to do this is to check both states in the ReadyStateChange event, and when one of these states appears, delete the ReadyStateChange event handle (which guarantees that the event will not be processed two times):

  var script = document.createelement ("script")      Script.type = "Text/javascript";      Internet Explorer      script.onreadystatechange = function () {            if (script.readystate = = "Loaded" | | Script.readystate = = "complete") {                  script.onreadystatechange = null;                  Alert ("Script loaded.");            }      ;      SCRIPT.SRC = "File1.js";      document.getElementsByTagName ("Head") [0].appendchild (script);

In most cases, you want to invoke a function to implement the dynamic loading of a JavaScript file. The following function encapsulates the functionality required by the standard implementation and IE implementations:

function Loadscript (URL, callback) {            var script = document.createelement ("script")            Script.type = "text/ JavaScript ";            if (script.readystate) {//ie                  script.onreadystatechange = function () {                        if (script.readystate = = "Loaded" | | Script.readystate = = "complete") {                              script.onreadystatechange = null;                              Callback ();                        }                 };            } else {//others                  script.onload = function () {                  callback ();}            ;      }      script.src = URL;      document.getElementsByTagName ("Head") [0].appendchild (script);      }

This function receives two parameters: the URL of the JavaScript file, and a callback function that fires when the JavaScript receive is complete. The property check is used to determine which event to monitor. The final step is to set the SRC attribute and add the <script> element to the page. This loadscript () function uses the following method:

Loadscript ("File1.js", function () {            alert ("File is loaded!");      });

You can load many JavaScript files dynamically on the page, but be aware that the browser does not guarantee the order in which the files are loaded. Of all the major browsers, only Firefox and opera guarantee that the scripts are executed in the order you specify. Other browsers will download and run different code files in the order in which they are returned by the server. You can concatenate the download operations together to ensure their order, as follows:

Loadscript ("File1.js", function () {            loadscript ("File2.js", function () {                  loadscript ("File3.js", function () {                        alert ("All Files is loaded!");});      

This code waits until File1.js is available to start loading file2.js, and so file2.js starts loading file3.js after it is available. While this approach works, it's still a bit cumbersome to download and execute a lot of files. If the order of multiple files is important, a better way is to connect the files to a file in the correct order. Standalone files can download all the code at once (since this is done asynchronously, there is no loss in using a large file).

Dynamic scripting loads the most common pattern in non-blocking JavaScript downloads, because it can be cross-browser and easy to use.

Using XMLHttpRequest (XHR) objects

This technique first creates a Xhr object, then downloads the JavaScript file, and then injects the JavaScript code into the page with a dynamic <script> element. The following is a simple example:

 var xhr = new XMLHttpRequest ();      Xhr.open ("Get", "File1.js", true); Xhr.onreadystatechange = function () {if (xhr.readystate = = 4) {if (Xhr.status >= && Amp Xhr.status < 300 | |                        Xhr.status = = 304) {var script = document.createelement ("script");                        Script.type = "Text/javascript";                        Script.text = Xhr.responsetext;                  Document.body.appendChild (script);      }            }      }; Xhr.send (null); 

This code sends a GET request to the server to get the File1.js file. The onReadyStateChange event handler checks whether the readystate is 4, and then checks that the HTTP status code is not valid (2XX indicates a valid response, and 304 represents a cached response). If a valid response is received, a new <script> element is created and its Text property is set to the ResponseText string received from the server. Doing so will actually create a <script> element with inline code. Once the new <script> element is added to the document, the code is executed and ready to be used. The main advantage of this approach is that you can download JavaScript code that is not executed immediately. Since the code is returned outside of the <script> tag (in other words, not constrained by the <script> tag), it is not automatically executed after downloading, which allows you to postpone execution until everything is ready. Another advantage is that the same code does not throw an exception in all modern browsers. The main limitation of this approach is that JavaScript files must be placed in the same domain as the page and cannot be downloaded from CDNs (CDN refers to "content Delivery network"), and large web pages typically do not use XHR script injection technology.

The recommended way to load a large amount of JavaScript into a page is in two steps: The first step is to include the code required to load the JavaScript dynamically, and then load the part of the page that you want to initialize in addition to the JavaScript. This part of the code is as small as possible and may contain only the Loadscript () function, which is downloaded and run very quickly and does not cause much disruption to the page. When the initial code is ready, use it to load the rest of the JavaScript. For example:

  <script type= "Text/javascript" src= "loader.js" ></script>      <script type= "Text/javascript" >            loadscript ("The-rest.js", function () {                  application.init ();            });      </script>

Place this code before the body's close label </body>. There are several advantages to this: first, as discussed earlier, this ensures that JavaScript runs without affecting the rest of the page display. Second, when the second part of the JavaScript file completes the download, all the necessary DOM for the application is created and ready to be accessed, avoiding the use of additional event handling (such as window.onload) to know if the page is ready. Another option is to embed the Loadscript () function directly in the page, which avoids another HTTP request. For example:

  <script type= "Text/javascript" > Function loadscript (URL, callback) {var script = Docum                  Ent.createelement ("script") Script.type = "Text/javascript"; if (script.readystate) {//ie script.onreadystatechange = function () {i                              F (script.readystate = = "Loaded" | |                                    Script.readystate = = "complete") {script.onreadystatechange = null;                              Callback ();                  }                        };                        } else {//others script.onload = function () {callback ();                  };                  } script.src = URL;            Document.getelementsbytagname_r ("Head") [0].appendchild (script);        } loadscript ("The-rest.js", function () {application.init ();    }); </script>

If you decide to use this method, it is recommended that you use "YUI Compressor" or a similar tool to reduce the initialization script to the minimum byte size. Once the page initialization code is downloaded, you can also use the Loadscript () function to load the additional function functions required for the page.

Non-blocking JavaScript scripting and extension knowledge

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.