{"rowid": 276, "title": "Your jQuery: Now With 67% Less Suck", "contents": "Fun fact: more websites are now using jQuery than Flash.\n\njQuery is an amazing tool that\u2019s made JavaScript accessible to developers and designers of all levels of experience. However, as Spiderman taught us, \u201cwith great power comes great responsibility.\u201d The unfortunate downside to jQuery is that while it makes it easy to write JavaScript, it makes it easy to write really really f*&#ing bad JavaScript. Scripts that slow down page load, unresponsive user interfaces, and spaghetti code knotted so deep that it should come with a bottle of whiskey for the next sucker developer that has to work on it. \n\nThis becomes more important for those of us who have yet to move into the magical fairy wonderland where none of our clients or users view our pages in Internet Explorer. The IE JavaScript engine moves at the speed of an advancing glacier compared to more modern browsers, so optimizing our code for performance takes on an even higher level of urgency.\n\nThankfully, there are a few very simple things anyone can add into their jQuery workflow that can clear up a lot of basic problems. When undertaking code reviews, three of the areas where I consistently see the biggest problems are: inefficient selectors; poor event delegation; and clunky DOM manipulation. We\u2019ll tackle all three of these and hopefully you\u2019ll walk away with some new jQuery batarangs to toss around in your next project.\n\nSelector optimization\n\nSelector speed: fast or slow?\n\nSaying that the power behind jQuery comes from its ability to select DOM elements and act on them is like saying that Photoshop is a really good tool for selecting pixels on screen and making them change color \u2013 it\u2019s a bit of a gross oversimplification, but the fact remains that jQuery gives us a ton of ways to choose which element or elements in a page we want to work with. However, a surprising number of web developers are unaware that all selectors are not created equal; in fact, it\u2019s incredible just how drastic the performance difference can be between two selectors that, at first glance, appear nearly identical. For instance, consider these two ways of selecting all paragraph tags inside a
with an ID.\n\n$(\"#id p\");\n\n$(\"#id\").find(\"p\");\n\nWould it surprise you to learn that the second way can be more than twice as fast as the first? Knowing which selectors outperform others (and why) is a pretty key building block in making sure your code runs well and doesn\u2019t frustrate your users waiting for things to happen.\n\nThere are many different ways to select elements using jQuery, but the most common ways can be basically broken down into five different methods. In order, roughly, from fastest to slowest, these are:\n\n\n\t$(\"#id\"); \nThis is without a doubt the fastest selector jQuery provides because it maps directly to the native document.getElementbyId() JavaScript method. If possible, the selectors listed below should be prefaced with an ID selector in conjunction with jQuery\u2019s .find() method to limit the scope of the page that has to be searched (as in the $(\"#id\").find(\"p\") example shown above).\n\t$(\"p\");, $(\"input\");, $(\"form\"); and so on\nSelecting elements by tag name is also fast, since it maps directly to the native document.getElementsByTagname() method.\n\t$(\".class\"); \nSelecting by class name is a little trickier. While still performing very well in modern browsers, it can cause some pretty significant slowdowns in IE8 and below. Why? IE9 was the first IE version to support the native document.getElementsByClassName() JavaScript method. Older browsers have to resort to using much slower DOM-scraping methods that can really impact performance.\n\t$(\"[attribute=value]\");\nThere is no native JavaScript method for this selector to use, so the only way that jQuery can perform the search is by crawling the entire DOM looking for matches. Modern browsers that support the querySelectorAll() method will perform better in certain cases (Opera, especially, runs these searches much faster than any other browser) but, generally speaking, this type of selector is Slowey McSlowersons.\n\t$(\":hidden\");\nLike attribute selectors, there is no native JavaScript method for this one to use. Pseudo-selectors can be painfully slow since the selector has to be run against every element in your search space. Again, modern browsers with querySelectorAll() will perform slightly better here, but try to avoid these if at all possible. If you must use one, try to limit the search space to a specific portion of the page: $(\"#list\").find(\":hidden\");\n\n\nBut, hey, proof is in the performance testing, right? It just so happens that said proof is sitting right here. Be sure to notice the class selector numbers beside IE7 and 8 compared to other browsers and then wonder how the people on the IE team at Microsoft manage to sleep at night. Yikes.\n\nChaining\n\nAlmost all jQuery methods return a jQuery object. This means that when a method is run, its results are returned and you can continue executing more methods on them. Rather than writing out the same selector multiple times over, just making a selection once allows multiple actions to be run on it.\n\nWithout chaining\n\n$(\"#object\").addClass(\"active\");\n$(\"#object\").css(\"color\",\"#f0f\");\n$(\"#object\").height(300);\n\nWith chaining\n\n$(\"#object\").addClass(\"active\").css(\"color\", \"#f0f\").height(300);\n\nThis has the dual effect of making your code shorter and faster. Chained methods will be slightly faster than multiple methods made on a cached selector, and both ways will be much faster than multiple methods made on non-cached selectors. Wait\u2026 \u201ccached selector\u201d? What is this new devilry? \n\nCaching\n\nAnother easy way to speed up your code that seems to be a mystery to developers is the idea of caching your selectors. Think of how many times you end up writing the same selector over and over again in any project. Every $(\".element\") selector has to search the entire DOM each time, regardless of whether or not that selector had been previously run. Running the selection once and then storing the results in a variable means that the DOM only has to be searched once. Once the results of a selector have been cached, you can do anything with them.\n\nFirst, run your search (here we\u2019re selecting all of the
  • elements inside