"jquery" 15 developer-focused jquery development tips and insights

Source: Internet
Author: User
Tags tag name free cdn

In this article, we'll cover 15 tips to make your jquery more effective, most of which are about performance improvements, and hopefully you'll enjoy it!

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

A lot of innovation was used in the jquery project. The best way to improve performance is to use the latest version of jquery. Each new version contains an optimized bug fix. For us the only thing to do is to change the tag, why not?

We can also use the 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 the selector string, JavaScript loops, and built-in JavaScript APIs such as getElementById (), getElementsByTagName (), Getelementsbyclassname () Three ways to integrate the use. But modern browsers are starting to support Queryselectorall (), a method that understands CSS queries and provides significant performance gains.

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

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

Choosing an ID is the quickest way. If you need to use the class name, then you'd better take the tag name, which will be quicker. Especially on old browsers and mobile devices.

Accessing the DOM is the slowest way for JavaScript applications, so use as little as possible. use the variable to save the selector, which is saved using the 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 extra convenience selectors, such as: Visible,:hidden,:animated and others, which are not legal CSS3 selectors. As a result, you cannot effectively use the Queryselectorall () method with these class libraries. To compensate for this problem, you need to first select the element, then filter, as follows:

$ (' a.button:animated '); Does not use Queryselectorall ()
$ (' A.button '). Filter (': Animated '); Uses it3. Using jquery objects as arrays

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 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 performance is your concern, use a simple for or while loop instead of $.each ()to make your code faster.

Checking the length is also a way to check if 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 properties

jquery provides a property that shows the selector used to make a chain.

$ (' #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 one 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 narrow collection.

5. Create an empty jquery object

Creating a new jquery space can greatly reduce the overhead. Sometimes, you might need to create an empty object and then add the object using the Add () method.

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

This is also the basis of the Quickeach method, which you can use in a faster way 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 only need to add a new method to the $.expr[': '] object. A great way to use it is mentioned in Waldek Mastykarz's blog: 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 the how to use it:
$ (' Li:random '). addclass (' Glow '); 7. Using CSS Hooks

The CSS Hooks API is a way to provide developers with the means to get and set specific CSS values. Using it, you can hide the browser-specific execution 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);

Better yet, people have created a support CSS Hooks class Library

8. Using a custom Delete method

You may have heard of jquery's removal plugin, which allows you to add special effects to your animations. The only drawback 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 you execute a method in a class library, 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 a problem and the button will disappear, not a panel. Using the $.proxy method, you can write code like this:

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

$ (' #panel button '). Click (function () {$.proxy ()
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 value returned by the above code, the faster the page loads. You can consider optimizing your code by removing unnecessary extraneous elements

11. Turn your code into a jquery plugin

If you have 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 to reuse the code and help you organize your code effectively. Create a plugin code as follows:

(function ($) {
$.fn.yourpluginname = function () {
Your Code goes here
return this;
};
}) (JQuery);

You can read more about the development tutorials here.

12. Set global Ajax as default

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

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 ();
*/

You can check this article in detail:

    • How to quickly create an Ajax "load" picture effect
    • 5 Online Ajax "load in" Rotate Icon Builder tool
13. Using the delay () method in animations

The chain 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 like this:
$ (' #elem '). Animate ({width:200}). Delay (. Animate ({margintop:100});

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

You can refer to this article: JQuery animations

14. Make reasonable use of the data property of HTML5

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

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

In order to access the 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: using HTML5 and jquery plugin quicksand to achieve a cool StarCraft 2 class display effect

jquery document for 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 properties:

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

But for older browsers, this is not good news. Because they don't support it. But we can use jquery's plugin to provide support once local storage is not available. This approach enables local storage functions to function properly.


Source: >  

From for notes (Wiz)

"jquery" 15 developer-focused jquery development tips and insights

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.