search
HomeWeb Front-endJS TutorialjQuery Performance Optimization Guide (2)_jquery

4,对直接的DOM操作进行限制
 
这里的基本思想是在内存中建立你确实想要的东西,然后更新DOM 。
这并不是一个jQuery最佳实践,但必须进行有效的JavaScript操作 。直接的DOM操作速度很慢。

例如,你想动态的创建一组列表元素,千万不要这样做,如下所示:

var top_100_list = [...], // 假设这里是100个独一无二的字符串
$mylist = $("#mylist"); // jQuery 选择到
    元素
for (var i=0, l=top_100_list.length; i
  $mylist.append("
  • " + top_100_list[i] + "
  • ");
    }

    我们应该将整套元素字符串在插入进dom中之前先全部创建好,如下所示:

    var top_100_list = [...],$mylist = $("#mylist"), top_100_li = ""; // 这个变量将用来存储我们的列表元素
    for (var i=0, l=top_100_list.length; i
       top_100_li += "
  • " + top_100_list[i] + "
  • ";
    }
    $mylist.html(top_100_li);
    注:记得以前还看过一朋友写过这样的代码:

    for (i = 0; i

        var $myList = $('#myList');

        $myList.append('This is list item ' + i);

    }

    呵呵,你应该已经看出问题所在了。既然把#mylist循环获取了1000次!!!
     

    5,冒泡
     

    除非在特殊情况下, 否则每一个js事件(例如:click, mouseover等.)都会冒泡到父级节点。
    当我们需要给多个元素调用同个函数时这点会很有用。

    代替这种效率很差的多元素事件监听的方法就是, 你只需向它们的父节点绑定一次。

    比如, 我们要为一个拥有很多输入框的表单绑定这样的行为: 当输入框被选中时为它添加一个class

    传统的做法是,直接选中input,然后绑定focus等,如下所示:

    $("#entryform input").bind("focus", function(){
        $(this).addClass("selected");
    }).bind("blur", function(){
        $(this).removeClass("selected");
    });

    当然上面代码能帮我们完成相应的任务,但如果你要寻求更高效的方法,请使用如下代码:

    $("#entryform").bind("focus", function(e){
        var $cell = $(e.target); // e.target 捕捉到触发的目标元素
        $cell.addClass("selected");
    }).bind("blur", function(e){
        var $cell = $(e.target);
        $cell.removeClass("selected");
    });
    通过在父级监听获取焦点和失去焦点的事件,对目标元素进行操作。
    在上面代码中,父级元素扮演了一个调度员的角色, 它可以基于目标元素绑定事件。
    如果你发现你给很多元素绑定了同一个事件监听, 那么现在的你肯定知道哪里做错了。
     
    同理,在Table操作时,我们也可以使用这种方式加以改进代码:
    普通的方式:

    $('#myTable td').click(function(){
        $(this).css('background', 'red');
    });
     改进方式:

    $('#myTable').click(function(e) {

         var $clicked = $(e.target);

         $clicked.css('background', 'red');

    });

    假设有100个td,在使用普通的方式的时候,你绑定了100个事件。
    在改进方式中,你只为一个元素绑定了1个事件,
    至于是100个事件的效率高,还是1个事件的效率高,相信你也能自行分辨了。
     
     

    6,推迟到 $(window).load
     

    jQuery는 개발자에게 매우 매력적인 기능을 제공합니다. $(document).ready 아래에 무엇이든 걸 수 있습니다.
    $(document).rady는 실제로 유용하지만 다른 요소를 다운로드하기 전에 페이지가 렌더링될 때 실행될 수 있습니다.
    페이지가 항상 로드되는 경우 $(document).ready 함수로 인해 발생했을 가능성이 높습니다.

    jQuery 함수를 $(window).load 이벤트에 바인딩하면 페이지가 로드될 때 CPU 사용량을 줄일 수 있습니다.
    모든 HTML(

    $(창).load(함수(){
    // 페이지가 완전히 로드된 후 초기화되는 jQuery 함수
    });

    드래그 앤 드롭, 시각 효과 및 애니메이션, 숨겨진 이미지 미리 로드 등과 같은 일부 특수 효과 기능이 이 기술에 적합합니다.

    7, JavaScript 압축
    JavaScript 파일을 압축하고 최소화하세요.
    온라인 압축 주소: http://dean.edwards.name/packer/
    압축하기 전에 코드가 표준화되었는지 확인하세요. 그렇지 않으면 실패할 수 있습니다. Js 오류가 발생합니다.
    이걸로 jQuery 성능 최적화 가이드(2)를 마치고, 가이드(3)를 진행 중입니다....
    여러분도 자신만의 아이디어가 있다고 생각합니다. 공유해 주세요. 이메일: cssrain@gmail.com
    Statement
    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
    JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

    Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

    Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

    JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

    Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

    I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

    How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

    This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

    JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

    JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

    The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

    The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

    Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

    JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

    Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

    Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

    See all articles

    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 Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools