jQuery performance optimization suggestions

     You are not unfamiliar with jQuery, the most popular javascript class library, and as long as front-end developers must use or have contact with it more or less, in this article, with reference to some materials and actual use efficiency, I will introduce some high-level writing skills. The principles of quality jQuery code will not only tell you how to write it, but also why it is written, I hope you will find it helpful.

    First, pay attention to adding the var keyword when defining jQuery variables

This is not only jQuery, but all javascript development process, you need to pay attention, please do not define it as follows:
$loading = $('#loading'); //This is a global definition, I don't know where it is unlucky to refer to the same Variable name, it will be depressed to death
Second, please use a var to define variables
If you use multiple variables, please define as follows:

   var page = 0,

   $loading = $('#loading'),   

   $body = $('body');

Don't add a var keyword to every variable, unless you have a serious obsessive- compulsive
disorder
The $ sign before the variable is as follows:

var $loading = $('#loading');
The advantage of defining it like this here is that you can effectively prompt yourself or other users who read your code, which is a jQuery variable.

Fourth, DOM operation, please remember to cache (cache)
In the development of jQuery code, we often need to operate the DOM. DOM operation is a process that consumes resources, and many people like to use jQuery like this:

$('#loading').html('完毕');
$('#loading').fadeOut();

There is no problem with the code, and you can run the result normally, but note here that every time you define and call $('#loading'), you actually create a new variable. If you need to reuse it, remember to be sure To define it into a variable, this can effectively cache the variable content, as follows:

var $loading = $('#loading');
$loading.html('完毕');$loading.fadeOut();


This will perform better.
5. Using the chain operation The
above example, we can write more concisely:

var $loading = $('#loading');
$loading.html('完毕').fadeOut();

6. Simplify the jQuery code and
try to integrate some codes together, please do not code like this:

// !!反面人物
$button.click(function(){
    $target.css('width','50%');
    $target.css('border','1px solid #202020');
    $target.css('color','#fff');
});


It should be written like this:

$button.click(function(){
    $target.css({'width':'50%','border':'1px solid #202020','color':'#fff'});
});


7. Avoid using global type selectors.
Do not write as follows: $('.something > *');
This is better: $('.something').children();
8. Do not stack multiple IDs
please Do not write as follows: $('#something #children');
This is enough: $('#children');
9. Use logical judgments || or && to speed up.
Do not write as follows:

if(!$something) {
    $something = $('#something ');
}


This way the writing performance is better:

$something= $something|| $('#something');


10. Use as little code as possible
Instead of writing this: if(string.length > 0){..} instead of
writing this: if(string.length){..} 11. Try to use
the .on method
For new versions of the jQuery library, please use .on, and any other methods are ultimately implemented using .on.
12. Try to use the latest version of jQuery The
latest version of jQuery has better performance, but the latest version may not support ie6/7/8, so you need to choose according to the actual situation.
13. Try to use native Javascript
If you can also use native Javascript to implement the functions provided by jQuery, it is recommended to use native javascript to implement it.
14. Always inherit from the #id selector
This is the golden rule of jQuery selectors. The fastest way to select an element with jQuery is to select it by its ID.

$('#content').hide();


Or inherit from ID selector to select multiple elements:

$('#content p').hide();


15. Use tag in front of class The
second fastest selector in jQuery is the tag selector (eg $('head')), because it comes directly from the native Javascript method getElementByTagName(). So it's best to always use tag to modify class (and don't forget the nearest ID)

var receiveNewsletter = $('#nslForm input.on');


The class selector in jQuery is the slowest because it traverses all DOM nodes in IE. Try to avoid using class selectors. Don't use tags to modify IDs either. The following example iterates over all div elements to find the node with id 'content':

var content = $('div#content'); // very slow, don't use


Using ID to modify ID is also superfluous:

var traffic_light = $('#content #traffic_light'); // very slow, don't use


16. Use subqueries
to cache parent objects for future use

 

var header = $('#header');
var menu = header.find('.menu');
// 或者
var menu = $('.menu', header);


17. Optimize selectors to apply Sizzle's "right-to-left" model
Since version 1.3, jQuery has adopted the Sizzle library, which is very different from the previous version in the selector engine. It replaces the "right-to-left" model with a "left-to-right" model. Make sure that the rightmost selector is specific, and the left selector is more general:

var linkContacts = $('.contact-links div.side-wrapper');


instead of using

var linkContacts = $('a.contact-links .side-wrapper');


18. Using find() instead of using context to find
the .find() function is indeed faster. But if a page has many DOM nodes, it may take more time to search back and forth:

var divs = $('.testdiv', '#pageBody'); // 2353 on Firebug 3.6
var divs = $('#pageBody').find('.testdiv'); // 2324 on Firebug 3.6 - The best time
var divs = $('#pageBody .testdiv'); // 2469 on Firebug 3.6


Nineteen, write your own selectors
If you often use selectors in your code, then extend jQuery's $.expr[':'] object and write your own selectors. In the following example, I create an abovethefold selector to select invisible elements:

$.extend($.expr[':'], {
 abovethefold: function(el) {
  return $(el).offset().top < $(window).scrollTop() + $(window).height();
 }
});
var nonVisibleElements = $('div:abovethefold'); // 选择元素


20. Caching jQuery Objects Cache
your frequently used elements:


var header = $ ('# header');
var divs = header.find ('div');
var forms = header.find ('form');

 

When doing DOM insertion, wrap all elements into one element

21. Direct DOM manipulation is slow. Change the HTML structure as little as possible.

 

var menu = '<ul id="menu">';
for (var i = 1; i < 100; i++) {
menu += '<li>' + i + '</li>';
}
menu += '</ul>';
$('#header').prepend(menu);
// 千万不要这样做:
$('#header').prepend('<ul id="menu"></ul>');
for (var i = 1; i < 100; i++) {
$('#menu').append('<li>' + i + '</li>');


}
22. Although jQuery does not throw exceptions, developers should also check objects

 

Although jQuery doesn't throw a lot of exceptions to the user, developers shouldn't rely on it either. jQuery usually performs a bunch of useless functions before determining whether an object exists. So before making a series of references to an object, you should first check whether the object exists.
23. Use direct functions instead of their equivalents
For better performance, you should use direct functions such as $.ajax() instead of $.get(), $.getJSON() , $.post(), because the next few will call $.ajax().
24. Cache jQuery results for later use
You will often get a javasript application object - you can use App. to save your frequently selected objects for future use:


App.hiddenDivs = $('div.hidden');
// Then call in your app:
App.hiddenDivs.find('span');


25. Use jQuery's internal function data() to store state
Don't forget to use the .data() function to store information:


$('#head').data('name', 'value');
// later call in your app:
$('#head').data('name');


Twenty-six, use the jQuery utility function
Don't forget the simple and practical jQuery utility function. My favorites are $.isFunction(), $isArray() and $.each().
27. Add a "JS" class to the HTML block
When jQuery is loaded, first add a "JS" class to the HTML

$('HTML').addClass('JS');


You can only add CSS styles if the user has JavaScript enabled. E.g:

/* in css */
.JS #myDiv{display:none;}


So when JavaScript is enabled, you can hide the entire HTML content and use jQuery to do what you want (eg: collapse certain panels or expand when the user clicks on them). And when Javascript is not enabled, the browser renders all the content, and the search engine crawlers tick all the content. I will use this technique more in the future.
Twenty-eight, defer to $(window).load
Sometimes using $(window).load() is faster than $(document).ready(), because the latter does not wait for all DOM elements to be downloaded before executing. You should test it before using it.
29. Use Event Delegation
When you have many nodes in a container and you want to bind an event to all nodes, delegation is very suitable for such application scenarios. With Delegation, we just need to bind the event at the parent and see which child node (target node) triggered the event. This becomes very convenient when you have a table with a lot of data and you want to set events on td nodes. First get the table, then set the delegation event for all td nodes:

$("table").delegate("td", "hover", function(){
$(this).toggleClass("hover");
});


30. Use shorthand for ready event
If you want to compress js plugins and save every byte, you should avoid using $(document).onready()

// Also don't use
$(document).ready(function (){
// code
});
// you can shorten it like this:
$(function (){
// code
});


Thirty-one, jQuery unit testing
The best way to test JavaSript code is to test it by humans. But you can use some automated tools like Selenium, Funcunit, QUit, QMock to test your code (especially plugins). I want to discuss this topic in another topic because there is so much to say.
32. Standardize your jQuery code
Often standardize your code, see which query is slower, and replace it. You can use the Firebug console. You can also use jQuery's shortcut functions to make testing easier:


// Shortcut to log data in Firebug console
$.l($('div'));

 

// Get UNIX timestamp
$.time();

// Record execution time in Firebug
$.lt();
$('div');
$.lt();

// Put the code block in a for loop to test execution time
$.bm("var divs = $('.testdiv', '#pageBody');"); // 2353 on Firebug 3.6


Thirty-three, using HMTL5
The new HTML5 standard brings a more lightweight DOM structure. The lighter structure means less traversal and better loading performance using jQuery. So please use HTML5 if possible.
Thirty-four, if you add styles to more than 15 elements, add style tags to DOM elements directly.
To add styles to a few elements, the best way is to use jQuery's css() function. However, when adding styles to more than 15 elements, it is more efficient to add style tags directly to the DOM. This method avoids hard coding in the code.


$('<style type="text/css"> div.class { color: red; } </style>')
.appendTo('head');


35. Avoid loading redundant code
It is a good idea to put Javascript code in different files and only load them when needed. This way you don't load unnecessary code and selectors. Also easy to manage code.
36. Compress into one main JS file to keep downloads to a minimum
When you have determined which files should be loaded, package them into one file. This can be done automatically with some open source tools like Minify (integrated with your backend code) or online tools like JSCompressor, YUI Compressor or Dean Edwards JS packer can compress files for you. My favorite is JSCompressor.
37. Use native Javasript when you need it.
Using jQuery is a great thing, but don't forget it's also a framework for Javascript. So you can also use native Javascript functions when necessary in jQuery code for better performance.
Thirty-eight, slow loading content can not only improve the loading speed, but also improve SEO optimization (Lazy load content for speed and SEO benefits)
Use Ajax to load your website, which can save server-side loading time. You can start with a common sidebar widget

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326889143&siteId=291194637