High-performance JavaScript

Source: Internet
Author: User

Other things cannot be handled by the browser while JavaScript is running

Page life cycle

The advent of <script> tags allows the download and parsing of the entire page to wait for script parsing and running, no matter how the JavaScript code is introduced

        document.write ("The date is" + (new  date ()). toDateString ());     </script></p>

<div>
<script src= "1.js" ></script>
</div>

</body>

Analytics: Browser Resolution page = = encountered p + browser stop, run JS code + browser continue to parse Div + encountered js, src attribute download js, run JS code

In the process of downloading parsing and running JS code, page parsing and user interaction are completely blocked.

<HTML><Head>    <title>Script Example</title>    <-- Example of inefficient script positioning-->    <Scripttype= "Text/javascript"src= "File1.js"></Script>    <Scripttype= "Text/javascript"src= "File2.js"></Script>    <Scripttype= "Text/javascript"src= "File3.js"></Script>    <Linkrel= "stylesheet"type= "Text/css"href= "Styles.css"></Head><Body><P>Hello world!</P></Body></HTML>

The browser does not render any part of the page until it encounters the <body> tag.

Illustration: The original browser does not support parallel download JS file

Although IE8 above the first browser supports parallel download, that is, a <script> tag does not have to block <script> tags, but JavaScript downloads still have to block the download process for other resources, for example. and also need all the JS code download execution After the page will continue to parse

Improve one: Put the script at the bottom. This allows the page display to be transmitted to the user before the download executes the parsing JS code.

<HTML><Head>    <title>Script Example</title>    <Linkrel= "stylesheet"type= "Text/css"href= "Styles.css"></Head><Body><P>Hello world!</P><-- Example of recommended script positioning--><Scripttype= "Text/javascript"src= "File1.js"></Script><Scripttype= "Text/javascript"src= "File2.js"></Script><Scripttype= "Text/javascript"src= "File3.js"></Script></Body></HTML>

HTTP request: Download a 100k file faster than download four 25k files, the joint handle of Yui library

<HTML><Head>    <title>Script Example</title>    <Linkrel= "stylesheet"type= "Text/css"href= "Styles.css"></Head><Body><P>Hello world!</P><-- Example of recommended script positioning--><Scripttype= "Text/javascript"src= "Http://yui.yahooapis.com/combo?2.7.0/build/yahoo/yahoo-min.js&2.7.0/build/event/event-min.js"></Script></Body></HTML>

Non-blocking mode one:

Although downloading a large JavaScript file produces only one HTTP request, it locks the browser for a large period of time.

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 several ways to achieve this effect.

Specifies that the <script> of the Defer property starts the download immediately, but the code does not execute immediately until the DOM is loaded

<HTML><Head>    <title>Script Defer Example</title></Head><Body><Scriptdefer>Alert ("defer");</Script><Script>Alert ("Script");</Script><Script>window.onload= function() {alert ("Load"); }; </Script></Body></HTML>

The order of browser output that supports defer: "Script", "defer" and "load".

Output order of browsers that do not support defer: "Defer", "script" and "load"

Dynamic scripting elements (that is, using the DOM method to create a script)

    var script = document.createelement ("script");     = "Text/javascript";     = "File1.js";    document.getElementsByTagName ("Head") [0].appendchild (script);

The point of the technology is that no matter where the download is initiated, the download and operation of the file will not block other page processes.

The Ff/opera/chrome Load event:

    var script = document.createelement ("script");     = "Text/javascript";     //     function  () {        alert ("Script loaded!") );    };     = "File1.js";    Document.getelementsbytagname_r ("Head") [0].appendchild (script);

ReadyStateChange event status in IE: (5 kinds of values):

Slightly

Compatible version:

    functionloadscript (URL, callback) {varScript = document.createelement ("Script") Script.type= "Text/javascript"; if(script.readystate) {//IEScript.onreadystatechange =function () {                if(Script.readystate = = "Loaded" | | script.readystate = = "complete") {Script.onreadystatechange=NULL;                Callback ();        }            }; } Else{//OthersScript.onload =function() {callback ();        }; } script.src=URL; Document.getelementsbytagname_r ("Head") [0].appendchild (script); }

Note, however, that the browser does not guarantee the order in which the files are loaded, but you can use the following method to ensure sequential loading:

    function () {        loadscript() (function () {             loadscript () {                 alert ( "All Files is loaded!" );            });        });    });

If the order of multiple files is important, the best way is to merge the files into one file in the correct order

non-blocking mode two: XHR Script Injection

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

Two advantages:

1. 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.

2. The same code will 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.

Recommended non-blocking modes:

The first is to include the code needed to dynamically load the JavaScript (such as Loadscript), and then load the part of the page initialization that is required in addition to JavaScript. For example:

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

Place this code before the body's close label </body>. There are several advantages to doing so:

First, make sure that JavaScript runs without affecting the other parts of the page display.

Second, avoid using additional event handling (such as window.onload) to see if the page is ready.

The second way:

High-performance JavaScript

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.