Home > Web Front-end > JS Tutorial > body text

Sharing examples of JS performance optimization techniques

小云云
Release: 2018-03-13 15:58:19
Original
1288 people have browsed it
  1. The script should be placed after the page element code

    No matter whether the current JavaScript code is embedded or in an external link file, the downloading and rendering of the page must stop and wait for the script Execution complete. The longer the JavaScript execution process takes, the longer the browser waits to respond to user input. The reason why browsers block when downloading and executing scripts is that the script may change the namespace of the page or JavaScript, which will affect the content of subsequent pages.

  2. Avoid global lookup

        function search() {
            //当我要使用当前页面地址和主机域名
            alert(window.location.href + window.location.host);
        }
        //最好的方式是如下这样  先用一个简单变量保存起来
        function search() {
            var location = window.location;
            alert(location.href + location.host);
        }
    Copy after login
  3. Type conversion

    般最好用”" + 1来将数字转换成字符串,虽然看起来比较丑一点,但事实上这个效率是最高的,性能上来说:
    Copy after login

("" + ) > String() > .toString() > new String() "

"
    var myVar = "3.14159",
    str = "" + myVar, //  to string  
    num=+myVar,       // to number
    i_int = ~ ~myVar,  //  to integer  
    f_float = 1 * myVar,  //  to float  
    b_bool = !!myVar,  /*  to boolean - any string with length 
                            and any number except 0 are true */
    array = [myVar];  //  to array
"
Copy after login
  1. Multiple type declarations

    All variables can be used in JavaScript Declared with a single var statement, it is a combined statement to reduce the execution time of the entire script. Just like the above code, the above code format is also quite standardized, making it clear at a glance.

    #Clone through template elements instead of createElement
  2. Many people like to use document.write in JavaScript to generate content for the page. In fact, this is less efficient. If you need to insert HTML directly, you can find one. Container elements, such as specifying a p or span, and setting their innerHTML to insert their own HTML code into the page. Usually we may use strings to write HTML directly to create nodes. In fact, 1: the code cannot be guaranteed. Effectiveness, 2: String operation efficiency is low, so the document.createElement() method should be used. If there are ready-made template nodes in the document, the cloneNode() method should be used, because after using the createElement() method, you need To set the attributes of multiple elements, use cloneNode() to reduce the number of attribute settings - also if you need to create many elements, you should prepare a template node first

        var frag = document.createDocumentFragment();
        for (var i = 0; i < 1000; i++) {
            var el = document.createElement(&#39;p&#39;);
            el.innerHTML = i;
            frag.appendChild(el);
        }
        document.body.appendChild(frag);
        //替换为:
        var frag = document.createDocumentFragment();
        var pEl = document.getElementsByTagName(&#39;p&#39;)[0];
        for (var i = 0; i < 1000; i++) {
            var el = pEl.cloneNode(false);
            el.innerHTML = i;
            frag.appendChild(el);
        }
        document.body.appendChild(frag);
    Copy after login

    Be careful when using closures. Package
  3. Case of closure

    document.getElementById(&#39;foo&#39;).onclick = function(ev) { };
    Copy after login

    Combining control conditions and control variables when looping
  4. for ( var x = 0; x < 10; x++ ) {};
    Copy after login
  5. When we want to add something to this Before looping, we found that there are several operations that the JavaScript engine needs to occur in each iteration: 1: Check whether x exists 2: Check whether x is less than 10 3: Increase x by 1

    Improvement

    var x = 9;
    do { } while( x-- );
    Copy after login

    Avoid comparing to null
  6. Since JavaScript is weakly typed, it does not do any automatic type checking, so if you see code that compares to null, try Use the following techniques to replace:

    1. If the value should be a reference type, use the instanceof operator to check its constructor 2. If the value should be a basic type, use typeof to check its type 3. If it is an object Contains a specific method name, use the typeof operator to ensure that the method with the specified name exists on the object

    Respect the ownership of the object
  7. Because JavaScript can Modifying any object can override the default behavior in unpredictable ways, so if you are not responsible for maintaining an object, its objects or its methods, then you should not modify it. Specifically:

    1. Do not add attributes to instances or prototypes. 2. Do not add methods to instances or prototypes. 3. Do not redefine existing methods. 4. Do not repeatedly define methods that have been implemented by other team members. Never modify them. From the objects you own, you can create new functionality for the object by: 1. Creating a new object containing the required functionality and using it to interact with related objects 2. Creating a custom type and inheriting the type that needs to be modified, You can then add extra functionality to the custom type

    Use literals
  8.     var aTest = new Array(); //替换为
        var aTest = [];
        var aTest = new Object; //替换为
        var aTest = {};
        var reg = new RegExp(); //替换为
        var reg = /../;
        //如果要创建具有一些特性的一般对象,也可以使用字面量,如下:
        var oFruit = new O;
        oFruit.color = "red";
        oFruit.name = "apple";
        //前面的代码可用对象字面量来改写成这样:
        var oFruit = { color: "red", name: "apple" };
    Copy after login
  9. Shorten negative detection
  10.     if (oTest != &#39;#ff0000&#39;) {
            //do something
        }
        if (oTest != null) {
            //do something
        }
        if (oTest != false) {
            //do something
        }
        //虽然这些都正确,但用逻辑非操作符来操作也有同样的效果:
        if (!oTest) {
            //do something
        }
    Copy after login
  11. Release javascript object
  12. 随着实例化对象数量的增加,内存消耗会越来越大。所以应当及时释放对对象的引用,让GC能够回收这些内存控件。 对象:obj = null 对象属性:delete obj.myproperty 数组item:使用数组的splice方法释放数组中不用的item

  13. 巧用||和&&布尔运算符

        function eventHandler(e) {
            if (!e) e = window.event;
        }
        //可以替换为:
        function eventHandler(e) {
            e = e || window.event;
        }
        
        
        
        if (myobj) {
            doSomething(myobj);
        }
        //可以替换为:
        myobj && doSomething(myobj);
    Copy after login
  14. switch语句相对if较快

  15. 每条语句末尾须加分号

相关推荐:

js性能优化技巧_javascript技巧

The above is the detailed content of Sharing examples of JS performance optimization techniques. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!