15 jquery Development Tips and insights worthy of developer attention "Classic Collection" _jquery

Source: Internet
Author: User
Tags tag name free cdn

This article summarizes 15 jquery development techniques and tips that are worth the attention of developers. Very incisive and practical! Share to everyone for your reference, specific as follows:

In this article, we'll introduce 15 techniques to make your jquery more effective, most of which are about performance improvement, and I hope everyone will like it!

1. Try to use the latest version of the jquery class library

A lot of innovation has been used in the jquery project. The best way to improve performance is to use the latest version of jquery. Each new release contains an optimized bug fix. The only thing for us to do is to modify the tag, why not?
We can also use a free CDN service, for example, Google to store the jquery class library.

<!--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, the way to return DOM elements was to parse selector strings, JavaScript loops, and built-in JavaScript APIs, such as getElementById (), getElementsByTagName (), Getelementsbyclassname () Three ways of integration use. But modern browsers are starting to support Queryselectorall (), a method that understands CSS queries and can lead to significant performance improvements.

However, we should avoid using complex selectors to return elements. Not to mention that many users use older versions of browsers to force jquery to handle the DOM tree. This is a very slow way.

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

Selecting IDs is the quickest way. If you need to use the class name, you'd better take the tag name, which is faster. Especially on old browsers and mobile devices.

Accessing the DOM is the slowest way that JavaScript is applied, so use it sparingly. Use variables to save the selector, which will be saved using the cache. Better performance.

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

Another worthwhile thing to do is that jquery gives you a lot of extra convenience selectors, such as: Visible,:hidden,:animated and others, these are not legitimate CSS3 selectors. As a result, you cannot use the Queryselectorall () method effectively using these libraries. To make up for this problem, you need to select the element first, then filter it as follows:

$ (' a.button:animated ');  does not use Queryselectorall ()
$ (' A.button '). Filter (': Animated ');  Uses it

3. Array mode using jquery objects

The result of running the selector is a jquery object. However, the jquery class library makes you feel like you are using an array that defines the index and the 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 performance is your concern, use a simple for or while loop to process instead of $.each (), which will make your code faster.

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

if (buttons) {//is always true
  //does something
}
if (buttons.length) {//True only if buttons contains Elements
  //do something
}

4. Selector properties

jquery provides a property that shows the selector that is used to make a chained type.

$ (' #container li:first-child '). Selector
//#container li:first-child
$ (' #container Li '). Filter (': First-child '). Selector
//#container Li.filter (: First-child)

Although the above example is for the same element, the selector is completely different. The second is actually illegal and you can't use it to create an object. Can only be used to show that the filter method is used to shrink collection.

5. Create an empty jquery object

Creating a new jquery space can greatly reduce overhead. Sometimes you might want 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 for the Quickeach method, which you can use faster than each ().

6. Select a random element

As I mentioned above, jquery adds its own selector filter. In addition to the class library, you can add your own filters. You just need to add a new method to the $.expr[': ' Object. A great way to use this is Waldek Mastykarz's blog: Create a selector that returns a random element. 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 are how to use it:
$ (' li:random '). addclass (' Glow ');

7. Using CSS Hooks

The CSS Hooks API is a way for developers to get and set specific CSS values. With it, you can hide browser-specific execution and use a unified interface to access specific attributes.

$.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 the browser actually understands:
$ (' #rect '). CSS (' Borderradius ', 5);

Better yet, people have created a library that supports CSS hooks classes

8. Use a custom Delete method

You may have heard of the jquery removal plugin, which allows you to add special effects to your animations. The only downside is that your visitors need to load another JavaScript file. Fortunately, you can simply copy the effect from the plugin and add it to the Jquery.easing object as follows:

$.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 disadvantage of using the callback method is that when 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>

Execute 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, the button will disappear, not the panel. Using the $.proxy method, you can write code like this:

$ (' #panel '). FadeIn (function () {
  //Using $.proxy to bind this:
  $ (' #panel button '). Click ($.proxy (function () {
    //This points to #panel
    $ (this). fadeout ();
  },this));


That's the right thing to do. The $.proxy method accepts two parameters, your initial approach, and the context. Read more $.proxy in the docs here.

10. Determine if the page is too complex

A very simple truth about complex pages, the slower the load. You can use the following code to check your page content:

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

The smaller the number returned by the above code, the faster the Web page will load. You can consider optimizing your code by removing unwanted extraneous elements.

11. Convert your code into a jquery plugin

If you're going to spend a certain amount of time developing a jquery code, you can consider turning the code into a plug-in. This will help you reuse your code and help you organize your code effectively. Create a plug-in code as follows:

(function ($) {
  $.fn.yourpluginname = function () {
    //Your code goes here
    ;
(JQuery);

You can read more development tutorials here.

12. Set global Ajax as default

If you develop AJAX programs, you definitely need to have "load" display to inform the user, Ajax is in progress, we can use the following code for unified management, as follows:

Ajaxsetup is useful to setting general defaults:
$.ajaxsetup ({
  URL      : '/ajax/',
  dataType  : ' JSON '
});
$.ajaxstart (function () {
  showindicator ();
  Disablebuttons ();
});
$.ajaxcomplete (function () {
  hideindicator ();
  Enablebuttons ();
});
*
  ///Additional methods can use:
  $.ajaxstop ();
  $.ajaxerror ();
  $.ajaxsuccess ();
  $.ajaxsend ();
*/

13. Use the delay () method in the animation

A chain-style animation effect is a powerful feature of jquery. But one of the missing details is that you can add delays between animations, as follows:

This is wrong:
$ (' #elem '). Animate ({width:200},function () {
  settimeout (function () {
    $ (' #elem '). Animate ({margintop:100});
  },2000);
Do it as this:
$ (' #elem '). Animate ({width:200}). Delay. Animate ({margintop:100});

jquery animations help us a lot, otherwise we have to deal with a bunch of details ourselves, set up timtout, handle attribute values, track animation changes, and so on.

14. Reasonable use of HTML5 data properties

The Data property of HTML5 can help us to insert it. Particularly suitable for data exchange at the front and back end. jquery recently released the data () method, can effectively use the HTML5 properties, to automatically get the information. Here's an example:

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

To access the data you need to invoke the following code:

$ ("#d1"). Data ("role"); "Page"
$ ("#d1"). Data ("Lastvalue");//
$ ("#d1"). Data ("hidden");//true;
$ ("#d1"). Data ("Options"). Name; "John";

If you want to see the actual example, please refer to this tutorial:

html5+jquery plugin Quicksand Achieve cool StarCraft 2 class display effect:http://www.jb51.net/article/85050.htm

15. Local Storage and jquery

Local storage is a super simple API. Simply add your data to the Localstorage global properties:

Localstorage.somedata = "This are going to be saved across page refreshes and browser restarts";

But this is not good news for older browsers. Because they don't support it. But we can use jquery's plug-ins to provide support once local storage is unavailable. This way you can make the local storage function work properly.

These are the 15 jquery development tips we've covered. I hope this article will help you with the jquery program design.

More interested readers of jquery-related content can view the site's topics: A summary of Ajax usage in jquery, a summary of jquery table (table) operations tips, a summary of jquery drag-and-drop effects and techniques, a summary of jquery extension techniques, jquery Common Classic Effects Summary "jquery animation and special effects usage Summary", "jquery selector usage Summary" and "jquery common Plug-ins and Usage summary"

I hope this article will help you with the jquery program design.

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.