jQuery Tips and Tricks you Must Memorize – Performance
Posted on July 17, 2011 | Comments Off on jQuery Tips and Tricks you Must Memorize – Performance
Storing Data
Use data method and avoid storing data inside the DOM. Some developers have a habit of storing data in the HTML attributes like ex.:
$('selector').attr('alt', 'data being stored'); // later the data can be retrieved using: $('selector').attr('alt');
HTML attributes is not meant to store data like that and the “alt” as a parameter name does not really make sense. The right alternative in most cases is using the data method in jQuery. It allows you to associate data with an element on the page.
$('selector').data('paramtername', 'data being stored'); // then later getting the data with $('selector').data('paramtername');
This approach allows you to store data with meaningful names and it is more flexible as you can store as much data as you want on any element on the page. For more information about data() and removeData()
Make code simpler using group queries
A useful way to make the code simpler and easier to read is by grouping the queries for elements that need the same treatment.
// Don't do it like this as it takes up unnecessary space and takes time to write $('div.close').click(doSomething); $('button.close').click(doSomething); $('input.close').click(doSomething); // Simply use group queries in the selector if you have to //apply same operation to them all $('div.close, button.close, input.close') .click(doSomething);
Cache jQuery Objects
Caching an object before working with it is essential for performance. You should neverdo like this:
<li>Description: <input type="text" name="description" value="" /></li> ... $('#shopping_cart_items input.text').css('border', '3px dashed yellow'); $('#shopping_cart_items input.text').css('background-color', 'red'); $('#shopping_cart_items input.text').val("text updated");
In stead cache the object and work on it. The example below should really use chaining but it is just for illustration.
var input_text = $('#shopping_cart_items input.text'); input_text.css('border', '3px dashed yellow'); input_text.css('background-color', 'red'); input_text.val("text updated"); //same with chaining: var input_text = $('#shopping_cart_items input.text'); input_text .css('border', '3px dashed yellow') .css('background-color', 'red') .val("text updated");
How to make sure an image has loaded properly
You can do this by using the .load() method on an “img” element and put a callback function in it. In the example below the “src” attribute of an image tag is changed to load a new image and attaches a simple load function. This technique can fx. be useful when building a captcha form validator.
$('#myImage').attr('src', 'image.jpg').load(function() { alert('Image Loaded'); //perform action that is dependant of image being fully loaded });