Performance js

转贴:https://10up.github.io/Engineering-Best-Practices/javascript/#performance

Performance

Writing performant code is absolutely critical. Poorly written JavaScript can significantly slow down and even crash the browser. On mobile devices, it can prematurely drain batteries and contribute to data overages. Performance at the browser level is a major part of user experience which is part of the 10up mission statement.

Only Load Libraries You Need

JavaScript libraries should only be loaded on the page when needed. jquery-1.11.1.min.js is 96 KB. This isn‘t a huge deal on desktop but can add up quickly on mobile when we start adding a bunch of libraries. Loading a large number of libraries also increases the chance of conflictions.

Use jQuery Wisely

jQuery is a JavaScript framework that allows us easily accomplish complex tasks such as AJAX and animations. jQuery is great for certain situations but overkill for others. For example, let‘s say we want to hide an element:

document.getElementById( ‘element‘ ).style.display = ‘none‘;

vs.

jQuery( ‘#element‘ ).hide();

The non-jQuery version is much faster and is still only one line of code.

Try to Pass an HTMLElement or HTMLCollection to jQuery Instead of a Selection String

When we create a new jQuery object by passing it a selection string, jQuery uses it‘s selection engine to select those element(s) in the DOM:

jQuery( ‘#menu‘ );

We can pass our own HTMLCollection or HTMLElement to jQuery to create the same object. Since jQuery does a lot of magic behind the scenes on each selection, this will be faster:

jQuery( document.getElementById( ‘menu‘ ) );

Cache DOM Selections

It‘s a common JavaScript mistake to reselect something unnecessarily. For example, every time a menu button is clicked, we do not need to reselect the menu. Rather, we select the menu once and cache it‘s selector. This applies whether you are using jQuery or not. For example:

non-jQuery Uncached:

var hideButton = document.getElementsByClassName( ‘hide-button‘ )[0];
hideButton.onclick = function() {
    var menu = document.getElementById( ‘menu‘ );
    menu.style.display = ‘none‘;
}

non-jQuery Cached:

var menu = document.getElementById( ‘menu‘ );
var hideButton = document.getElementsByClassName( ‘hide-button‘ )[0];
hideButton.onclick = function() {
    menu.style.display = ‘none‘;
}

jQuery Uncached:

var $hideButton = jQuery( ‘.hide-button‘ );
$hideButton.on( ‘click‘, function() {
    var $menu = jQuery( ‘#menu‘ );
    $menu.hide();
});

jQuery Cached:

var $menu = jQuery( ‘#menu‘ );
var $hideButton = jQuery( ‘.hide-button‘ );
$hideButton.on( ‘click‘, function() {
    $menu.hide();
});

Notice how in cached versions we are pulling the menu selection out of the event handler so it only happens once. Non-jQuery cached is not surprisingly the fastest way to handle this situation.

Event Delegation

Event delegation is the act of adding one event listener to a parent node to listen for events bubbling up from children. This is much more performant than adding one event listener for each child element. Here is an example:

Without jQuery:

document.getElementById( ‘menu‘ ).addEventListener( ‘click‘, function( event ) {
    if( event.target && event.target.nodeName === ‘LI‘ ) {
        // Do stuff!
    }
});

With jQuery:

jQuery( ‘#menu‘ ).on( ‘click‘, ‘li‘, function() {
    // Do stuff!
});

The non-jQuery method is as usual more performant. You may be wondering why we don‘t just add one listener to <body> for all our events. Well, we want the event to bubble up the DOM as little as possible for performance reasons. This would also be pretty messy code to write.

Design Patterns back to top

Standardizing the way we structure our JavaScript allows us to collaborate more effectively with one another. Using intelligent design patterns improves maintainability, code readability, and even helps to prevent bugs.

Don‘t Pollute the Window Object

Adding methods or properties to the window object or the global namespace should be done carefully. window object pollution can result in collisions with other scripts. We should wrap our scripts in closures and expose methods and properties to window decisively.

When a script is not wrapped in a closure, the current context or this is actuallywindow:

window.console.log( this === window ); // true
for ( var i = 0; i < 9; i++ ) {
    // Do stuff
}
var result = true;
window.console.log( window.result === result ); // true
window.console.log( window.i === i ); // true

When we put our code inside a closure, our variables are private to that closure unless we expose them:

( function() {
    for ( var i = 0; i < 9; i++ ) {
        // Do stuff
    }

    window.result = true;
})();

window.console.log( typeof window.result !== ‘undefined‘ ); // true
window.console.log( typeof window.i !== ‘undefined‘ ); // false

Notice how i was not exposed to the window object.

Use Modern Functions, Methods, and Properties

It‘s important we use language features that are intended to be used. This means not using deprecated functions, methods, or properties. Whether we are using a JavaScript or a library such as jQuery or Underscore, we should not use deprecated features. Using deprecated features can have negative effects on performance, security, maintainability, and compatibility.

For example, in jQuery jQuery.live() is a deprecated method:

jQuery( ‘.menu‘ ).live( ‘click‘, function() {
    // Clicked!
});

We should use jQuery.on() instead:

jQuery( ‘.menu‘ ).on( ‘click‘, function() {
    // Clicked!
});

Another example in JavaScript is escape() and unescape(). These functions were deprecated. Instead we should use encodeURI()encodeURIComponent(),decodeURI(), and decodeURIComponent().

Code Style & Documentation back to top

We conform to WordPress JavaScript coding standards.

In the absence of an adopted core standard for JavaScript documentation, we follow the JSDoc3 standards.

Unit and Integration Testing back to top

At 10up, we generally employ unit and integration tests only when building applications that are meant to be distributed. Writing tests for client themes usually does not offer a huge amount of value (there are of course exceptions to this). When we do write tests, we use QUnit which is a WordPress standard.

Libraries back to top

There are many JavaScript libraries available today. Many of them directly compete with each other. We try to stay consistent with what WordPress uses. The following is a list of primary libraries used by 10up.

DOM Manipulation

jQuery - Our and WordPress‘s library of choice for DOM manipulation.

Utility

Underscore - Provides a number of useful utility functions such as clone(),each(), and extend(). WordPress core uses this library quite a bit.

Frameworks

Backbone - Provides a framework for building complex JavaScript applications. Backbone is based on the usage of models, views, and collections. WordPress core relies heavily on Backbone especially in the media library. Backbone requires Underscore and a DOM manipulation library (jQuery)

时间: 2024-10-16 23:56:46

Performance js的相关文章

Performance --- 前端性能监控

阅读目录 一:什么是Performance? 二:使用 performance.timing 来计算值 三:前端性能如何优化? 四:Performance中方法 五:使用performane编写小工具 回到顶部 一:什么是Performance? Performance是前端性能监控的API.它可以检测页面中的性能,W3C性能小组引入进来的一个新的API,它可以检测到白屏时间.首屏时间.用户可操作的时间节点,页面总下载的时间.DNS查询的时间.TCP链接的时间等.因此我们下面来学习下这个API.

页面性能监控之performance

页面性能监测之performance author: @TiffanysBear 最近,需要对业务上的一些性能做一些优化,比如降低首屏时间.减少核心按钮可操作时间等的一些操作:在这之前,需要建立的就是数据监控的准线,也就是说一开始的页面首屏数据是怎样的,优化之后的数据是怎样,需要有一个对比效果.此时,performance 这个API就非常合适了. performance Performance 接口可以获取到当前页面中与性能相关的信息.它是 High Resolution Time API 的

基于HTML5实现的Heatmap热图3D应用

Heatmap热图通过众多数据点信息,汇聚成直观可视化颜色效果,热图已广泛被应用于气象预报.医疗成像.机房温度监控等行业,甚至应用于竞技体育领域的数据分析. 已有众多文章分享了生成Heatmap热图原理,可参考<How to make heat maps>和<How to make heat maps in Flex>,本文将介绍基于HTML5技术的实现方式,主要基于Cavans和WebGL这两种HTML5的2D和3D技术的应用,先上最终例子实现的界面效果和操作视频: 实现Heat

网站优化记录

网站优化实录 网站优化,从多方面优化,分为前端优化部分和服务器(后台)优化. 现在主要讲前端优化的部分,这是从我自己在做网站优化的时候记录下来的.首先的是,前端优化方面,从多个方面,主要是图片文件,文件链接,html代码结构,css优化等.使用工具比较多,先是用于检测网站性能的工具. 检测网站性能的工具和方法: 通过检测,可以更准确找出网站加载慢的愿意和改善的方案. 1.最简单的方法. webkit内核(谷歌)游览器 F12 - 调出调试工具--选中Network ,然后刷新网站,可以看到具体的

Web 自动化测试与智能爬虫利器:PhantomJS 简介与实战

估计部分同学没听过这个工具,那先简单介绍下它的背景与作用. 1.PhantomJS 是什么? PhantomJS是一个基于WebKit的服务器端JavaScript API,它无需浏览器的支持即可实现对Web的支持,且原生支持各种Web标准,如DOM 处理.JavaScript.CSS选择器.JSON.Canvas和可缩放矢量图形SVG.PhantomJS主要是通过JavaScript和CoffeeScript控制WebKit的CSS选择器.可缩放矢量图形SVG和HTTP网络等各个模块.Phan

测开之路七十六:性能测试蓝图之html

<!-- 继承base模板 -->{% extends 'base.html' %} {% block script %} <!-- 从cdn引入ace edter的js --> <script src="https://cdn.bootcss.com/ace/1.4.5/ace.js"></script> <script src="https://cdn.bootcss.com/ace/1.4.5/mode-python

[Transducer + Ramda] Write highly performance / functional code by using transducer-js and ramda.js libs

Tansducer-js lib A high performance Transducers implementation for JavaScript. Transducers are composable algorithmic transformations. They are independent from the context of their input and output sources and specify only the essence of the transfo

Optimize Cube.js Performance with Pre-Aggregations

转自:https://cube.dev/blog/high-performance-data-analytics-with-cubejs-pre-aggregations/ 可以了解 Pre-Aggregations的处理流程 This is an advanced tutorial. If you are just getting started with Cube.js, I recommend checking this tutorial first and then coming bac

[HTML 5 Performance] Measuring used JS heap size in chrome

In this lesson we will see how to measure the used JS heap size in chrome. This can be used for various needs from performance debugging to production monitoring of apps. function measureMemory() { console.log(`${performance.memory.usedJSHeapSize / M