15 jQuery development skills and experiences worthy of developers' attention

Source: Internet
Author: User
Document directory
  • 1. Try to use the latest jQuery class library
  • 2. Use a simple Selector
  • 3. Use jQuery objects in array Mode
  • 4. selector attributes
  • 5. Create an empty jQuery object
  • 6. Select a random element.
  • 7. Use CSS Hooks
  • 8. Use a custom deletion method
  • 9. $. proxy ()
  • 10. Determine if the page is too complex
  • 11. Convert your code into a jQuery plugin
  • 13. Use the delay () method in the animation
  • 14. Make Rational Use of HTML5 Data attributes
  • 15. Local Storage and jQuery

Date: 2011/11/16

In this article, we will introduce 15 tips to make jQuery more effective. I hope you will like the performance improvement!

1. Try to use the latest jQuery class library

The jQuery project uses a lot of innovations. The best way to improve performance is to use the latest version of jQuery. Each new version contains optimized bug fixes. The only thing we need to do is modify the tag. Why not?

We can also use a free CDN service, such as Google, to store jQuery class libraries.

<!-- Include a specific version of jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<!-- Include the latest version in the 1.6 branch -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
2. Use a simple Selector

Until recently, all the methods for returning DOM elements are to parse the selector string, javascript loops and built-in javascript APIs such as getElementbyId (), getElementsByTagName (), and getElementsByClassName. However, modern browsers are beginning to support querySelectorAll (). This method can understand CSS queryers and significantly improve performance.

However, we should avoid using complex selector to return elements. Not to mention that many users use older browsers to force jQuery to process the DOM tree. This method is very slow.

$('li[data-selected="true"] a')// Fancy, but slow 
$('li.selected a')// Better
$('#elem')// Best

Selecting id is the fastest way. If you need to use the class name, you 'd better include the tag name, which will be faster. Especially on old browsers and mobile devices.

Accessing the DOM is the slowest way for javascript applications, so try to use it as little as possible. Use variables to save the selector, which will be saved using cache. Better performance.

var buttons = $('#navigation a.button');  // Some prefer prefixing their jQuery variables with $: 
var $buttons = $('#navigation a.button');

Another thing worth doing is that jQuery gives you a lot of additional convenience selectors, such as: visible,: hidden,: animated, and others. These are not legal CSS3 selectors. The result is that you cannot use the querySelectorAll () method effectively by using these class libraries. To make up for this problem, you need to first select elements and then filter them, as shown below:

$('a.button:animated');// Does not use querySelectorAll() 
$('a.button').filter(':animated');// Uses it
3. Use jQuery objects in array Mode

The result of running the selector is a jQuery object. However, the jQuery class library makes you feel that you are using an array that defines the index and length.

// Selecting all the navigation buttons:
var buttons = $('#navigation a.button');

// We can loop though the collection:
for(var i=0;i<buttons.length;i++){
console.log(buttons[i]);// A DOM element, not a jQuery object
}

// We can even slice it:
var firstFour = buttons.slice(0,4);

If the performance is your concern, use simple for or while loops instead of $. each () to make your code faster.

Checking the length is also a way to check whether your collection contains elements.

if(buttons){// This is always true
// Do something
}

if(buttons.length){ // True only if buttons contains elements
// Do something
}
4. selector attributes

JQuery provides an attribute that shows the Selector Used for chain.

$('#container li:first-child').selector    // #container li:first-child
$('#container li').filter(':first-child').selector // #container li.filter(:first-child)

Although the preceding example targets the same element, the selector is completely different. The second is actually invalid. You cannot use it to create an object. The filter method can only be used to narrow down the collection.

5. Create an empty jQuery object

Creating a New jQuery space can greatly reduce the overhead. Sometimes, you may need to create an empty object and then use the add () method to add the object.

var container = $([]); 
container.add(another_element);

This is also the basis of the quickEach method. You can use this faster method instead of each ().

6. Select a random element.

As mentioned above, jQuery adds its own selector filter. In addition to class libraries, you can add your own filters. You only need to add a new method to the $. expr [':'] object. A great way to use it is mentioned in the blog of Waldek Mastykarz: Create a selector to return random elements. You can modify the following code:

(function($){
var random = 0;

$.expr[':'].random = function(a, i, m, r) {
if (i == 0) {
random = Math.floor(Math.random() * r.length);
}
return i == random;
};

})(jQuery);

// This is how you use it:
$('li:random').addClass('glow');
7. Use CSS Hooks

CSS hooks API is a method that allows developers to obtain and set specific CSS values. With it, you can hide the specific execution of the browser and use a unified interface to access specific properties. ,

$.cssHooks['borderRadius'] = {
get: function(elem, computed, extra){
// Depending on the browser, read the value of
// -moz-border-radius, -webkit-border-radius or border-radius
},
set: function(elem, value){
// Set the appropriate CSS3 property
}
};

// Use it without worrying which property the browser actually understands:
$('#rect').css('borderRadius',5);

What's better is that people have created a class library that supports CSS hooks.

8. Use a custom deletion method

You may have heard of jQuery's delete plug-in, which allows you to add special effects to your animation. The only drawback is that your visitor needs to load another javascript file. Fortunately, you can simply copy the effect from the plug-in and add it to the jQuery. easing object, as shown below:

$.easing.easeInOutQuad = function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
};

// To use it:
$('#elem').animate({width:200},'slow','easeInOutQuad');
9. $. proxy ()

One of the disadvantages of using the callback method is that after the method in the class library is executed, the context is set to another element, for example:

<div id="panel" style="display:none">
<button>Close</button>
</div>

Run the following code:

$('#panel').fadeIn(function(){
// this points to #panel
$('#panel button').click(function(){
// this points to the button
$(this).fadeOut();
});
});

You will encounter problems, and the button will disappear, not the panel. Using the $. proxy method, you can write the code as follows:

$('#panel').fadeIn(function(){
// Using $.proxy to bind this:

$('#panel button').click($.proxy(function(){
// this points to #panel
$(this).fadeOut();
},this));
});

In this way, the execution is correct. The $. proxy method accepts two parameters: Your initial method and context. For more information, see $. proxy in the docs ..

10. Determine if the page is too complex

A very simple principle is that, for complex pages, the loading speed slows down. You can use the following code to check your page content:

console.log( $('*').length );

The smaller the value returned by the code above, the faster the webpage loading speed. You can consider removing unnecessary elements to optimize your code.

11. Convert your code into a jQuery plugin

If you need to spend some time developing a piece of jQuery code, you can consider turning the code into a plug-in. This will help you reuse code and effectively help you organize code. The code for creating a plug-in is as follows:

(function($){
$.fn.yourPluginName = function(){
// Your code goes here
return this;
};
})(jQuery);

You can read more development tutorials here.

12. set global AJAX as the default

If you develop an ajax program, you must have a display like loading to inform users that ajax is in progress. We can use the following code for unified management:

// ajaxSetup is useful for setting general defaults:
$.ajaxSetup({
    url            : '/ajax/',
    dataType    : 'json'
});

$.ajaxStart(function(){
    showIndicator();
    disableButtons();
});

$.ajaxComplete(function(){
    hideIndicator();
    enableButtons();
});

/*
    // Additional methods you can use:
    $.ajaxStop();
    $.ajaxError();
    $.ajaxSuccess();
    $.ajaxSend();
*/

For details, refer to this article:

  • How to quickly create an AJAX "loaded" Image
  • Five online Ajax "loading" Rotating icon generator tools
13. Use the delay () method in the animation

The chained animation effect is the power of jQuery. However, you can add delays between animations, as shown below:

// This is wrong:
$('#elem').animate({width:200},function(){
    setTimeout(function(){
        $('#elem').animate({marginTop:100});
    },2000);
});

// Do it like this:
$('#elem').animate({width:200}).delay(2000).animate({marginTop:100});

JQuery animation has helped us a lot; otherwise we have to handle a bunch of details, set timtout, process attribute values, track animation changes, and so on.

You can refer to this article: jQuery animations

14. Make Rational Use of HTML5 Data attributes

The data attribute of HTML5 can help us insert data. It is particularly suitable for frontend and backend data exchange. The recently released data () method of jQuery can effectively use HTML5 attributes to automatically obtain data. The following is an example:

<div id="d1" data-role="page" data-last-value="43" data-hidden="true"
    data-options='{"name":"John"}'>
</div>

To access data, you need to call the following code:

$("#d1").data("role");// "page"
$("#d1").data("lastValue");// 43
$("#d1").data("hidden");// true;
$("#d1").data("options").name;// "John";

If you want to see the actual example, please refer to this tutorial: Use HTML5 and jQuery plug-in Quicksand to implement a cool Starcraft 2 Category Display Effect

JQuery document of data (): data () in the jQuery docs

15. Local Storage and jQuery

Local Storage is a super simple API. Simply add your data to the localStorage global attribute:

localStorage.someData = "This is going to be saved across page refreshes and browser restarts";

But for old browsers, this is not good news. Because they do not. However, you can use the jQuery plug-in to provide support once the local storage is unavailable. This method can make the local storage function work normally.

The above are the 15 jQuery development skills we have introduced. If you have more skills and comments, please leave a message below. Thank you for your support!

15 jQuery development skills and experiences worthy of developers' attention

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.