Home Web Front-end JS Tutorial Sharing examples of JS performance optimization techniques

Sharing examples of JS performance optimization techniques

Mar 13, 2018 pm 03:58 PM
javascript share Example

  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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to share Quark Netdisk to Baidu Netdisk? How to share Quark Netdisk to Baidu Netdisk? Mar 14, 2024 pm 04:40 PM

Quark Netdisk and Baidu Netdisk are very convenient storage tools. Many users are asking whether these two softwares are interoperable? How to share Quark Netdisk to Baidu Netdisk? Let this site introduce to users in detail how to save Quark network disk files to Baidu network disk. How to save files from Quark Network Disk to Baidu Network Disk Method 1. If you want to know how to transfer files from Quark Network Disk to Baidu Network Disk, first download the files that need to be saved on Quark Network Disk, and then open the Baidu Network Disk client. , select the folder where the compressed file is to be saved, and double-click to open the folder. 2. After opening the folder, click "Upload" in the upper left corner of the window. 3. Find the compressed file that needs to be uploaded on your computer and click to select it.

How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments Mar 25, 2024 am 11:41 AM

1. First, we enter NetEase Cloud Music, and then click on the software homepage interface to enter the song playback interface. 2. Then in the song playback interface, find the sharing function button in the upper right corner, as shown in the red box in the figure below, click to select the sharing channel; in the sharing channel, click the &quot;Share to&quot; option at the bottom, and then select the first &quot;WeChat Moments&quot; allows you to share content to WeChat Moments.

How to share files with friends on Baidu Netdisk How to share files with friends on Baidu Netdisk Mar 25, 2024 pm 06:52 PM

Recently, Baidu Netdisk Android client has ushered in a new version 8.0.0. This version not only brings many changes, but also adds many practical functions. Among them, the most eye-catching is the enhancement of the folder sharing function. Now, users can easily invite friends to join and share important files in work and life, achieving more convenient collaboration and sharing. So how do you share the files you need to share with your friends? Below, the editor of this site will give you a detailed introduction. I hope it can help you! 1) Open Baidu Cloud APP, first click to select the relevant folder on the homepage, and then click the [...] icon in the upper right corner of the interface; (as shown below) 2) Then click [+] in the &quot;Shared Members&quot; column 】, and finally check all

Mango tv member account sharing 2023 Mango tv member account sharing 2023 Feb 07, 2024 pm 02:27 PM

Mango TV has various types of movies, TV series, variety shows and other resources, and users can freely choose to watch them. Mango TV members can not only watch all VIP dramas, but also set the highest definition picture quality to help users watch dramas happily. Below, the editor will bring you some free Mango TV membership accounts for users to use, hurry up and take a look Take a look. Mango TV latest member account free sharing 2023: Note: These are the latest member accounts collected, you can log in directly and use them, do not change the password at will. Account number: 13842025699 Password: qds373 Account number: 15804882888 Password: evr6982 Account number: 13330925667 Password: jgqae Account number: 1703

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Solve the problem that Discuz WeChat sharing cannot be displayed Solve the problem that Discuz WeChat sharing cannot be displayed Mar 09, 2024 pm 03:39 PM

Title: To solve the problem that Discuz WeChat shares cannot be displayed, specific code examples are needed. With the development of the mobile Internet, WeChat has become an indispensable part of people's daily lives. In website development, in order to improve user experience and expand website exposure, many websites will integrate WeChat sharing functions, allowing users to easily share website content to Moments or WeChat groups. However, sometimes when using open source forum systems such as Discuz, you will encounter the problem that WeChat shares cannot be displayed, which brings certain difficulties to the user experience.

Share two installation methods for HP printer drivers Share two installation methods for HP printer drivers Mar 13, 2024 pm 05:16 PM

HP printers are essential printing equipment in many offices. Installing the printer driver on the computer can perfectly solve problems such as the printer being unable to connect. So how to install HP printer driver? The editor below will introduce you to two HP printer driver installation methods. The first method: download the driver from the official website 1. Search the HP China official website in the search engine, and in the support column, select [Software and Drivers]. 2. Select the [Printer] category, enter your printer model in the search box, and click [Submit] to find your printer driver. 3. Select the corresponding printer according to your computer system. For win10, select the driver for win10 system. 4. After downloading successfully, find it in the folder

How to share Tomato novel link How to share Tomato novel link Feb 27, 2024 pm 04:20 PM

Tomato Novels is a rich treasure house of novels, which gathers a large number of high-quality novel resources. Here, you can choose your favorite novels from many different types of novels according to your preferences. For those of you who love reading, this is undoubtedly a literary world where you can fly freely. Sometimes when you encounter your favorite reading material, it’s like sharing it with friends to read together, but many users don’t know exactly how to share it, so this tutorial guide will bring you a detailed introduction to the guide, for players who want to know more Come and read along with this article! How to share Tomato novels with friends? 1. Open Tomato Novel, click to enter the novel, and click the share icon in the upper right corner. 2. Select the sharing channel. Here I take sharing to WeChat friends as an example. 3. Click Share. 4. You can check

See all articles