As the number of rich Web applications grows, as well as users ' high expectations of fast interactive responses, developers start using JavaScript libraries to quickly and efficiently perform repetitive tasks. Applications One of the most popular JavaScript libraries is jquery. But the vast application of jquery poses another problem: what are the best practices and bad practices when using JavaScript libraries?
Background
In this article, I'll show you some good practices (at least I think) when writing, debugging, and reviewing JavaScript code. In fact, I chose 7 of the most common scenarios.
1, the use of CDN and its return address (fallback)
CDN represents the Content delivery network (Delivery network), a server that caches JavaScript files. After using a CDN, your application can use CDN caching whenever a new user initiates a request, without reloading the library file from your server. CDN services are available from Google, Microsoft, and jquery.
Given that the network is not always 100% reliable and that the server may be down for some reason, you have to make sure that even if these things happen, your application will still work. That's when we're going to use the fallback address: When the application can't find the cache, it will roll 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>
The 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 did not specify the URL protocol for HTTP but used//. This is because the CDN server supports HTTP and HTTPS, and if your site has SSL authentication, you can load the file normally without modification.
Also, as I mentioned earlier, we need a fallback address to prevent the CDN server from having problems.
<script>window.jquery | | document.write (' <script src= ' Script/localsourceforjquery "></script>")
Of course, you can also use require to configure the jquery you need, but I think that's fine.
2. Limit DOM Interaction
Using JavaScript to manipulate the DOM tree is performance-intensive. jquery is the same. So try to minimize the interaction with the DOM. When I helped a colleague improve the speed of data display, I saw him using a selector in a loop. This is a performance killer! That's what he wrote:
Containerdiv = $ ("#contentDiv");
for (var d =0 D < totalactions; d++)
{
containerdiv.append (<div><span class= ' Brilliantrunner ') > "+ D +" </span></div> ");
}
What's the problem? I see nothing wrong. And my colleague also said that the code is very happy to run! I'm really beeping the dog! When the totalactions is less than 50 o'clock, it does not detect any problems, but when it reaches 25000, the speed is reduced a lot, the reason (I also Google) is the DOM interaction into the loop.
For this feature (after multiple attempts fail) I replaced the direct DOM interaction in the loop with a push operation of an array, and then connected the array (join) with an empty string as a delimiter. Finally, the program is certainly becoming 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, caching
The most important and unique feature of jquery is its selector and how to find HTML elements in the DOM tree. However, I have seen many times that some developers call the same selector multiple times in the same function, such as $ ("#divid"). Although the jquery selection element is very fast, don't look for the same element every time. So, you can cache your elements like this:
var $divId = $ ("#divId")
Then in the next code, you can use the $divid.
For the following code:
var thefunction = function ()
{
$ ("#mydiv"). Toggleclass ("Zclass");
$ ("#mydiv"). Fadeout (a);
var thefunction2 = function ()
{
$ ("#mydiv"). Addattr ("name");
$ ("#mydiv"). FadeIn ();
We can make changes like this and use chained syntax to make it look prettier:
var mydiv =$ ("#mydiv");
var thefunction = function ()
{
mydiv. Toggleclass ("Zclass"). Fadeout (a);
var thefunction2 = function ()
{
mydiv.addattr ("name"). FadeIn ();
But then again, you don't have to cache everything every time. Look at the following example:
$ ("#link"). Click (function ()
{
$ (this). AddClass ("gored");
Here, I neither use $ ("#link"), or cache it, but use $ (this). Because in this case, the object I'm working on is the link itself.
4, Find and filter
Recently, I had some confusion when using find () to get a combination of jquery objects. I then found that the operation could be replaced with the filter () method. It is important to understand the difference between the two:
Find : will start with the selected element and look down the DOM tree
filter: is found in the jquery collection
5, End ()
I sometimes have to go back to the parent object to do some work when I'm chained to the jquery collection. For example, you're applying CSS to the second row of a table, and then you want to go back to the Table object and add some style to it. Once you've applied the style to the row, just use the end () method, and you'll automatically go back to the Table object and add a style to it.
(Translator Note: Find (), filter () and end () text is uppercase, in fact, should be lowercase)
6, Object literal quantity
When you manipulate CSS properties of elements through chained syntax, you can use object literals to improve performance. Like this code:
$ ("#myimg"). attr ("src", "thepath"). attr ("Alt", "the alt text");
After that, not only do you avoid manipulating DOM elements, but you don't have to call the relevant setting methods multiple times:
$ ("#myimg"). attr ({"src": "Thepath", "alt": "The Alt Text"});
7. Use CSS Class
Use CSS classes whenever possible rather than inline CSS code. I don't think there's any need for an illustration.
Hopefully this article will help you write better jquery apps that really help you.