转贴: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)

Performance js的更多相关文章

  1. You Don't Know JS: Scope & Closures(翻译)

    Chapter 1: What is Scope? 第一章:什么是作用域 One of the most fundamental paradigms of nearly all programming ...

  2. iOS-监听原生H5性能数据window.performance

    WebKit-WKWebView iOS8开始苹果推荐使用WKWebview作为H5开发的核心组件,以替代原有的UIWebView,以下是webkit基本介绍介绍: 介绍博客 Webkit H5 - ...

  3. 页面性能监控之performance

    页面性能监测之performance author: @TiffanysBear 最近,需要对业务上的一些性能做一些优化,比如降低首屏时间.减少核心按钮可操作时间等的一些操作:在这之前,需要建立的就是 ...

  4. Performance --- 前端性能监控

    阅读目录 一:什么是Performance? 二:使用 performance.timing 来计算值 三:前端性能如何优化? 四:Performance中方法 五:使用performane编写小工具 ...

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

    Heatmap热图通过众多数据点信息,汇聚成直观可视化颜色效果,热图已广泛被应用于气象预报.医疗成像.机房温度监控等行业,甚至应用于竞技体育领域的数据分析. http://www.hightopo.c ...

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

    Heatmap热图通过众多数据点信息,汇聚成直观可视化颜色效果,热图已广泛被应用于气象预报.医疗成像.机房温度监控等行业,甚至应用于竞技体育领域的数据分析. 已有众多文章分享了生成Heatmap热图原 ...

  7. drupal笔记

    $app_root :网站根目录 安装 汉化:1将汉化包放置drupal8\sites\default\files\translations下安装:2极简版的话需要在extend(扩展)中安装Inte ...

  8. [React] 10 - Tutorial: router

    Ref: REACT JS TUTORIAL #6 - React Router & Intro to Single Page Apps with React JS Ref: REACT JS ...

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

    <!-- 继承base模板 -->{% extends 'base.html' %} {% block script %} <!-- 从cdn引入ace edter的js --> ...

随机推荐

  1. Spark2.0 特征提取、转换、选择之一:数据规范化,String-Index、离散-连续特征相互转换

    数据规范化(标准化) 在数据预处理时,这两个术语可以互换使用.(不考虑标准化在统计学中有特定的含义). 下面所有的规范化操作都是针对一个特征向量(dataFrame中的一个colum)来操作的. 首先 ...

  2. 多个JS文件性能优化

    页面中引入的JS文件是阻塞式加载的,这样会影响页面性能.以下是JS文件性能优化方法: 一:将所有的<script>标签放到页面底部,也就是</body>闭合标签之前,这能确保在 ...

  3. [golang note] 函数定义

    普通函数定义 √ golang函数基本组成:关键字func.函数名.参数列表.返回值.函数体和返回语句. • 语法如下 func 函数名(参数列表) (返回值列表) { // 函数体 } • 示例如下 ...

  4. vim使用winmanager整合nerd tree和taglist

    winmanager插件安装 • 插件简介 winmanager is a plugin which implements a classical windows type IDE in Vim-6. ...

  5. smarty模板(转载)

    一.smarty的程序设计部分: 在smarty的模板设计部分我简单的把smarty在模板中的一些常用设置做了简单的介绍,这一节主要来介绍一下如何在smarty中开始我们程序设计.下载Smarty文件 ...

  6. 端口状态说明 LISTENING、ESTABLISHED、TIME_WAIT及CLOSE_WAIT

    TCP状态转移要点    TCP协议规定,对于已经建立的连接,网络双方要进行四次握手才能成功断开连接,如果缺少了其中某个步骤,将会使连接处于假死状态,连接本身占用的资源不会被释放.网络服务器程序要同时 ...

  7. [转]DNS服务器原理详解与Centos6.x下搭建DNS服务器

    转自:http://blog.it985.com/8958.html DNS 数据库的记录:正解,反解, Zone 的意义 通过DNS解析过程详解这篇文章,我们知道了要想访问www.zmit.cn,最 ...

  8. [转]美国最大婚恋交友网站eHarmony的机器学习实践

    转自:http://www.csdn.net/article/2015-03-19/2824267 上周,我去洛杉矶参加了一个机器学习的meetup,一位主讲是eHarmony公司(美国最大的婚恋交友 ...

  9. C++之操作Excel(抄录https://www.cnblogs.com/For-her/p/3499782.html)

    MFC操作Excel 下面的操作基于Excel2003 一.初始化操作 1.导入类库 点击查看->建立类向导-> Add Class...\From a type Library...-& ...

  10. 201453131《Java程序设计》实验三实验报告

    实验三 敏捷开发与XP实践 实验内容 •下载并学会使用git上传代码: •与同学结对,相互下载并更改对方代码,并上传: 实验步骤 下载并用git上传代码: •1.下载并安装好git,在cmd中输入gi ...