7 jQuery best practices and jquery Best Practices

Source: Internet
Author: User

7 jQuery best practices and jquery Best Practices
Background

In this article, I will introduce some good practices (at least I think so) when writing, debugging, and reviewing JavaScript code ). In fact, I chose seven of the most common scenarios.

  1. Use CDN and its return address (fallback)

Content Delivery Network (CDN) is a server that caches JavaScript files. After using CDN, your application can use CDN cache whenever a new user initiates a request, instead of reloading the library file from your server. Google, Microsoft, and JQuery provide CDN services.

Since the network is not always 100% reliable, and the server may be down for some reason, you must make sure that even if these events occur, your applications can still run normally. At this time, we need to use the rollback address: when the application cannot find the cache library, it will return back and use the Server File.

Google CDN is like this:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>

Microsoft CDN is like this:

<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"> </script>

It should be noted that we do not specify the URL protocol as http but use //. This is because the CDN server supports http and https. If your website has SSL authentication, you can load files without modification.

In addition, as I mentioned earlier, we also need a back-to-back address to prevent problems with the CDN server.

<script>Window.JQuery || document.write(&lsquo;<script src=&rdquo;script/localsourceforjquery&rdquo;></script>&rsquo;)

Of course, you can also use Require to configure the required jQuery, but I think this is also good.

  2. Restrict DOM interaction

Using JavaScript to operate the DOM tree results in performance consumption. The same applies to jQuery. Therefore, try to reduce interaction with DOM. When I helped a colleague improve the data display speed, I saw that he used a selector in a loop. This is a performance killer! He wrote:

containerDiv = $("#contentDiv");for(var d =0; d < TotalActions; d++){  containerDiv.append("<div><span class='brilliantRunner'>" +   d + "</span></div>");}

What's the problem? At first glance, there is no problem. My colleagues also said that this Code had a great time! I am a dog! When TotalActions is less than 50, no problem is detected; but when TotalActions reaches 25000, the speed is much lower, because (I also google) DOM interaction is placed in the loop.

For this function (after multiple failed attempts), I replaced the direct DOM interaction in the loop with an array push operation, and then joined the array with an empty string as the separator). Finally, the program becomes smoother and more efficient.

var myContent=[];for(var d = 0; d < TotalActions; d++){  myContent.push("<div><span class='brilliantRunner'>" + d + "</span></div>");}containerDiv.html(myContent.join(""));
  3. Cache

The most important and characteristic of jQuery is its selector and the method for searching HTML elements in the DOM tree. However, I have seen several times that some developers call the same selector multiple times in the same function, for example, $ ("# divid "). Although jQuery selects elements very quickly, do not search for the same elements every time. Therefore, you can cache your elements like this:

var $divId = $("#divId")

Then, you can use $ divId in the following code.

For the following code:

var thefunction = function(){    $("#mydiv").ToggleClass("zclass");    $("#mydiv").fadeOut(800);}var thefunction2 = function(){    $("#mydiv").addAttr("name");    $("#mydiv").fadeIn(400);}

We can modify it like this and use the chain syntax to make it look more beautiful:

var mydiv =$("#mydiv");var thefunction = function(){  mydiv.ToggleClass("zclass").fadeOut(800);}var thefunction2 = function(){  mydiv.addAttr("name").fadeIn(400);}

But you don't need to cache everything every time. See the following example:

$("#link").click(function(){     $(this).addClass("gored");}

Here, I neither use $ ("# link") or cache it, but use $ (this ). In this example, the object I operate on is the link itself.

  4. find and filter

Recently, when I used find () to obtain the combination of jQuery objects, I encountered some confusion. Then I found that this operation can be implemented by using the filter () method. It is important to understand the differences between the two:

Find: searches for the DOM tree filter from the selected element until it is found in the jQuery set.
  5. end ()

When performing chained operations in the jQuery collection, I sometimes need to return to the parent object for some operations. For example, you are applying CSS to the second row of a table and want to return to the table object and add some styles to it. After you apply a style to a row, you only need to use the end () method, and then you will automatically return to the table object and add the style to it at will!

(Note: find (), filter (), and end () are in upper case, which should be in lower case)

  6. Object literal volume

When you use the chained syntax to manipulate the CSS attributes of an element, you can use the object literal to improve the performance. For example, this Code:

$("#myimg").attr("src", "thepath").attr("alt", "the alt text");

As shown in the following figure, operations on DOM elements are not only avoided, but related setting methods are not required multiple times:

$("#myimg").attr({"src": "thepath", "alt": "the alt text"});
  7. Make good use of CSS

Try to use CSS classes instead of inline CSS code. I don't need an example to illustrate this.

  Last

I hope this article will help you write better jQuery applications.

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.