38 recommendations for optimizing jQuery performance

  • 2020-03-30 02:12:48
  • OfStack

var $loading = $('#loading');
4
Optimize the selector to fit the "right-to-left" model of Sizzle
Since version 1.3, jQuery has adopted the Sizzle library, which is very different from the way the previous version was presented on the selector engine. It replaces the right-to-left model with the left-to-right model. Make sure the right-most selector is specific and the left selector has a wider selection range:
var linkContacts = $('.contact-links div.side-wrapper');

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

Use find() instead of a context lookup
The.find() function is indeed faster. But if a page has many DOM nodes and needs to be searched back and forth, it may take more time:
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

Write your own selector
If you often use selectors in your code, extend jQuery's $.expr[':'] object and write your own selectors. In the following example, I created a abovethefold selector to select invisible elements:
$.extend($.expr[':'], {
 abovethefold: function(el) {
  return $(el).offset().top < $(window).scrollTop() + $(window).height();
 }
});
var nonVisibleElements = $('div:abovethefold'); //  Select elements 

Cache jQuery objects
Cache the elements you use most often:

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

When DOM insertion occurs, all elements are encapsulated into a single element

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


$('#loading').html(' The completion of ');
$('#loading').fadeOut();
0
}
22. Although jQuery does not throw exceptions, developers should also examine objects

Although jQuery does not throw a lot of exceptions to users, developers should not rely on it. JQuery typically performs a bunch of useless functions before determining whether an object exists or not. So before making a series of references to an object, you should check whether it exists or not.
23. Use direct functions, not their equivalents
For better performance, you should use direct functions like $.ajax() instead of $.get(),$.getjson (), and $.post(), because the next few will call $.ajax().
Cache the results of jQuery for later use
You will often get a javasript application object - you can use the App. To save the object you often select for future use:


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

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

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

26. Use jQuery utility functions
Don't forget the simple utility functions of jQuery. My favorites are $.isfunction (), $isArray(), and $.each().
27. Add a "JS" class to an HTML block
When jQuery loads, first add a class called "JS" to the HTML
$('HTML').addClass('JS');

You can only add CSS styles when the user has JavaScript enabled. Such as:

.JS #myDiv{display:none;}

So when JavaScript is enabled, you can hide the entire HTML content and use jQuery to do what you want (for example, fold up some panels or expand them when the user clicks on them). When Javascript is not enabled, the browser renders everything and the search engine crawler checks everything. I'll use this technique more in the future.
Defer to $(window).load
Sometimes $(window).load() is faster than $(document).ready() because it doesn't wait to execute before all the DOM elements have been downloaded. You should test it before you use it.
29. Use Event Delegation
Delegation is good for application scenarios where you have many nodes in a container and you want to bind an event to all nodes. With Delegation, we just need to bind the event at the parent level and see which child node (the target node) triggered the event. This is handy when you have a table with a lot of data and you want to set events on the td node. Get the table first, then set the delegation event for all td nodes:
$("table").delegate("td", "hover", function(){
$(this).toggleClass("hover");
});

Use the ready event abbreviation
If you want to compress the js plug-in to save every byte, you should avoid using $(document).onready()
//Don't use
$(document).ready(function (){
//  code 
});
//You can write it like this:
$(function (){
//  code 
});

31. JQuery unit tests
The best way to test JavaSript code is by people. But you can use automated tools like Selenium, Funcunit, QUit, and QMock to test your code (especially plug-ins). I want to talk about this in another topic because there's so much to say.
three Standardize your jQuery code
Often standardize your code, see which query is slow, and replace it. You can use the Firebug console. You can also use jQuery's shortcuts to make testing easier:

//A shortcut to record data in the Firebug console
$.l($('div'));
//Gets the UNIX timestamp
$.time();
//Log code execution time in Firebug
$.lt();
$('div');
$.lt();
//Place the code block in a for loop to test the execution time
$.bm("var divs = $('.testdiv', '#pageBody');"); // 2353 on Firebug 3.6

33. Using HMTL5
The new HTML5 standard brings a lighter DOM structure. The lighter structure means less traversal and better loading performance with jQuery. So use HTML5 if possible.
34. If you style more than 15 elements, directly add style tags to DOM elements
The best way to style a few elements is to use jQuey's CSS () function. However, when adding styles to more than 15 elements, it is more effective to add style tags directly to the DOM. This method avoids using hard code in your code.

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

35. Avoid loading extra code
It's a good idea to put Javascript code in different files and load it only when needed. This way you don't load unnecessary code and selectors. It's also easy to manage code.
36, compressed into a main JS file, will keep the number of downloads to the minimum
When you have identified which files should be loaded, package them into a file. Open source tools such as Minify(which integrates with your back-end code) or online tools such as JSCompressor, YUI Compressor, or Dean Edwards JS packer can automatically do this for you. My favorite is JSCompressor.
Use native javascript when needed
JQuery is a great thing to use, but don't forget that it's also a framework for Javascript. So you can use native Javascript functions when your jQuery code is needed for better performance.
Slow load not only improves load speed, but also improves SEO benefits.
Load your site with Ajax to save server load time. You can start with a common sidebar widget.


Related articles: