Some practical jQuery tricks

Source: Internet
Author: User
Tags shallow copy jquery library

jquery is now the most popular JavaScript library in web development, and with jquery and a large number of plugins, you can easily achieve a variety of brilliant effects.

This article will show you some practical tips to help you use jquery more effectively.

Tip 1: Use the latest version  

Each new version of jquery contains performance optimizations and bug fixes that you can use with the Google CDN Service hosted jquery library for ease of upgrade. There are two ways of doing this:

Include a specific version

HTML code
    1. < Script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"> </ Script >



contains the latest version of a branch (the jquery version of this method has a cache duration of only 1 hours and is not recommended for production environments)

HTML code
    1. < Script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></ script>



Tip 2: Using a simple selector  

Previously fetching DOM elements typically used jquery's getElementById (), getElementsByTagName (), and Getelementsbyclassname () methods. Today, all major browsers already support Queryselectorall (), a method that understands CSS queries. You should try to use this more optimal way.

JavaScript code
    1. $ (' li[data-selected= "true"] a ') //looks good, but slow
    2. $ (' li.selected a ') //Better method
    3. $ (' #ElementID) //Best



TIP 3: Caching The results of jquery  

If you have no other choice but to use the DOM selector, then you should cache the results of jquery. For example:

JavaScript code
    1. var selectedlistitem = $ (' li[data-selected= "true"]a ')



Now, the result of jquery has been cached to the variable "Selectedlistitem", which can be used multiple times without impacting performance.

Tip 4: Considerations for extending selectors with jquery  


jquery offers a number of extended selectors , such as visible, hidden, animated, and so on, which are not valid CSS3 selectors. If these selectors are used, the Queryselectorall () method can no longer be used. To avoid this, you can first select the element and then filter it. For example:

JavaScript code
    1. $ (' A.button:hidden '); //You cannot use Queryselectorall ()
    2. $ (' A.button '). Filter (': Hidden '); //Best Practices



The above results are the same, but the 2nd one is faster.

TIP 5: Use jquery objects like arrays  

The result of running a selector is a jquery object. However, with jquery you can make the results look more like an array, and you can define the index elements and lengths.

JavaScript code
    1. var  buttons = $ ( ' #navigation  a.button ' );  //selecting all the navigation b //selecting all  the navigation buttons   
    2. //  We can loop though the collection:   
    3. for (var  i=0;i<buttons.length;i++) {  
    4. Console.log (buttons[i])  // a dom element, not  a jquery object   
    5. }  



If you want to achieve higher performance, you can use a simple loop (or while statement) instead of $.each (), which will be several times faster than before.

Tip 6: Check if an element exists  

The only way to determine whether an element collection exists or contains elements is to check the length of the element.

JavaScript code
    1. if (buttons.length) { //True only if buttons contains elements
    2. //Do something}



Tip 7: Create a jquery empty object  

Creating a new jquery object can sometimes be a lot of overhead. However, you can create an empty object first, and then populate it with Add ().

JavaScript code
    1. var container = $ ([]);
    2. Container.add (another_element);



Tip 8: Count the number of DOM elements in a Web page  

If the page contains a large number of elements or content, the browser renders more time. You can count the number of DOM elements in the page by executing the following statement in the console:

JavaScript code
    1. Console.log ($ (' * '). length);



If the resulting value is small, the page renders faster. You can optimize by removing extraneous tags and unnecessary elements.

Tip 9: Turn your code into a jquery plugin  

If you want to encapsulate your jquery code as a jquery plugin for later reuse, you can create it with the following code:

JavaScript code
    1. function ($) {
    2. $.fn.yourpluginname = function() {
    3. //Your code goes here
    4. return this;
    5. };
    6. }) (JQuery);



TIP 10: Local Storage  

The Local storage is an API for storing information on the client. When used, you only need to use your data as a property of the Localstorage global object:

JavaScript code
    1. Localstorage.somedata = "This data was going to persist across page refreshes and browser restarts";



the old browser does not support the API, but there are a variety of jquery plugins available as alternatives. These plug-ins provide additional storage scenarios when Localstorage is not available. Here is an example:

JavaScript code
    1. //Check If "key" exists in the storage.
    2. var value = $.jstorage.get ("key");
    3. if (!value) {
    4. //If not-load the data from the server
    5. Value = Load_data_from_server ();
    6. //And save it
    7. $.jstorage.set ("key", value);



Tip 11:live Event handling  

Set an event handler for any element that matches the selector, even if it is added to the DOM after the initial page is loaded:

JavaScript code
    1. $ (' button.yourclassname '). Live (' click ', Yourfunctionname);



This allows the event handlers to automatically set the elements when they are loaded through Ajax or javascript:

JavaScript code
    1. $ (' button.yourclassname '). Die (' click ', Yourfunctionname);



Although the live event handler has some limitations compared to regular events, it is suitable for most situations. The live event supports jquery 1.3 and later.

Tip 12: Clone an Object  

Use the. Clone () method to clone Dom objects in javascript:

JavaScript code
    1. //Clone the DIV
    2. var cloned = $ (' #yourdivID '). Clone ();



The. Clone () method cannot clone a JavaScript object. If you are cloning a JavaScript object, you can use the following code:

JavaScript code
    1. //Shallow copy
    2. var newObject = Jquery.extend ({}, Oldobject);
    3. //Deep copy
    4. var newObject = Jquery.extend (true, {}, Oldobject);



Tip 13: Test hidden elements  

You can change the visibility of an element by using the. Hide () and. Show () methods. Use the following code to detect whether an element is visible:

JavaScript code
    1. if (Element). Is (": visible") = = "true") {
    2. //the element is Visible
    3. }



Tip 14: Find the nearest parent Div  

If you want to find out the parent div of an element (whether or not the DIV has an id), you can use this jquery selector:

JavaScript code
    1. $ ("#yourControl"). Closest ("div");



English Original:jQuery best Practices

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.