jQuery Performance Optimization Guide (2)_jquery
例如,你想动态的创建一组列表元素,千万不要这样做,如下所示:
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');});假设有100个td,在使用普通的方式的时候,你绑定了100个事件。$('#myTable').click(function(e) {
var $clicked = $(e.target);
$clicked.css('background', 'red');
});
在改进方式中,你只为一个元素绑定了1个事件,至于是100个事件的效率高,还是1个事件的效率高,相信你也能自行分辨了。
6,推迟到 $(window).loadjQuery는 개발자에게 매우 매력적인 기능을 제공합니다. $(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중국어 번역: http://rlog.cn/350 & http://cssrain.cn

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.

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.

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

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

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.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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
A free and powerful IDE editor launched by Microsoft

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
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools