All Tools

Optimize your jQuery selectors for best performance

Introduction

Over time, the data size has increased for nearly every application. Due to huge amount of data residing in various database servers, performance becomes the most important and integral part of any application. If the page takes lots of time to render the data, it creates a bad impression and results in loss of interest by the end users. There are different places where performance can be increased, including database code, server side code to process the data and client side code.
Application development has also gone through monumental change over time. The client calls REST API and the server automatically sends the data in JSON or some other format. It’s the responsibility of client side code to process and render it for display. Therefore, it’s pretty important to follow best practices for client side code in order to ensure best performance. jQuery is one of the most popular and most used client side libraries, so writing high performance jQuery code is of the utmost importance. One of the key areas of performance improvement is in the methods for selecting and manipulating HTML elements. jQuery selectors allow you to select and manipulate HTML element(s) quite easily. This post shows how to optimize your jQuery selectors for best performance.
Let’s begin!

Before we get into optimization tips, let me first give you a quick overview of the different categories of jQuery selectors. There is no official categorization, but they can be categorized in this way:

• ID selector $(‘#elementID’)
• Tag selector $(‘p’)
• Class selector $(‘.CSSClass’)
• Attribute selector $(‘[type="text"]‘)
• Pseudo selector $(‘:visible’)

Always use ID selector if possible

Accessing DOM is a very expensive operation, so it’s beneficial to minimize effort and time. As we all know, the ID attribute is unique for each HTML element on the page. In JavaScript document.getElementById() is the function that one would use to select the HTML element. It’s the fastest and the best way to select the element because it directly maps to the element. jQuery is a library written on top of JavaScript, which means that it internally calls the JavaScript functions to do the job. When you use ID as a selector in jQuery, it internally calls document.getElementById(). To select the HTML element with elm as ID, the jQuery code looks like this: $(“#elm”);
This method works well in all browsers, so it’s a good choice if you are using an older browser.

Cache your selector

Caching improves the performance of the application. You can cache data or objects for better performance. You can also cache your jQuery selectors for better performance using the ID as your selector (as mentioned in the previous tip). When you don’t cache the selector, jQuery must rescan the DOM to get the element. You may not feel the difference in small applications, but with large applications this becomes very critical. Let’s look at the process of caching objects in jQuery. The following simple line of code caches the selector and stores it in the $elm variable:

var $elm = $("#elm");

Now use the $elm variable instead of using the jQuery ID selector. Like this:

var $elm = $("#elm");
 $elm.addClass(‘dummy’);

Remember, the scope of a variable is limited to where it is defined. If it is defined as a global variable then you can use it anywhere in the jQuery code, but if it is inside a method the scope will be limited to that particular method only. Global caching is useful for elements which are frequently used in the code.

Define a context with jQuery selectors

By default, jQuery selectors perform their search within the DOM. But while defining the selector, you can pass the context, which limits the searching range for the jQuery selector. In other words, you are instructing jQuery to look into the context rather than beginning the search from the document root. This helps in speeding up the searching process which will definitely improve the performance. Passing the context is optional, but you should use it whenever you can.

Enough theory! Let’s take a look at a practical example. Consider the following HTML code:

<div id=”parent1”>
<div class=”child”> </div>
<div class=”child”> </div>
<div class=”child”> </div>
</div>

If you want to select all the div element with child class you can use the following jQuery code:

var $elm = $(".child");

The above code will search for elements with child class starting from the document root. It can be optimized by passing via an alternate selector. Like,

var $parent = $("#parent1");
 var $elm = $(".child", $parent);

This limits the search range, so now searching is limited to the div with ID parent1. The context argument can be a DOM element, a document, or a jQuery object. If you pass context, then jQuery will internally use the find method to retrieve the elements. So the above code is internally converted to:

var $elm = $parent.find(".child");

jQuery first checks if the passed context is a jQuery object. If it is, it calls the find() method on the given context. If the given context is a DOM element, it first converts it to a jQuery object and then executes the find() method. As such, it is better to pass the object as context instead of the DOM element because it will reduce the conversion time.

Don’t repeat your selectors

As mentioned earlier, you can cache the jQuery selectors which prevents you from repeating your selector. jQuery also offers chaining, which allows you to chain multiple methods in a single call. Consider the following jQuery code:

$("div").css("color", "red");
 $("div").css("font-size", "14px");
 $("div").text("New Text!");

Below is the first optimized version using caching:

var $div = $("div");
 $div.css("color", "red");
 $div.css("font-size", "14px");
 $div.text("New text goes here!");

Next is the second optimized version using chaining:

$("div").css({"color", "red", "font-size", "14px"}).text("New text goes here!");

Use class selector wisely

jQuery also provides a CSS class selector which allows you to select elements with a particular CSS class. This is again a very useful and popular selector as it allows you to select multiple elements at once. However, you have to be cautious while using class selector. The following jQuery code will select all the elements with “dummy” class applied to them:

$(".dummy")

In this case, jQuery has to scan the complete DOM to discover elements with dummy class. As mentioned earlier, traversing DOM is a very expensive process so it’s always better to minimize this effort. In this case, you can pass a tag name to reduce the searching scope. Like this:

$("div.dummy");

The above code tells jQuery to only give me the DIV elements with dummy CSS class applied. Though the class selector works quite well in modern browsers, older browsers have performance issues with class selector. That being said, it’s not always a good choice to add a tag name with class selector. Why?

In this example, jQuery will first search for all elements with class dummy and then filter records to only return those elements that are div elements. So when the dummy class is only meant for div elements, you need to specify the tag name in order to add an extra step of filtering. Keep in mind that this is only useful when the CSS class is applied to different HTML elements like span, paragraph and div.

Be very specific about selectors

Did you know that jQuery selectors are executed from right to left? In other words, the last selector will be executed first when there are multiple selectors. Consider the following example:

$("div.parent .child");

In this example, jQuery will first search for all elements with class child (last selector executed first) and then apply a filter to return only those elements which are div elements with a parent class applied. This is the optimized version:

$(".parent div.child");

Here we are more specific on the last selector, which helps to speed up performance!

Look for an alternative for the Pseudo selector

Pseudo class selectors are CSS selectors with a colon preceding them. They are also available with jQuery - :visible, :checked or :first. Pseudo selectors are useful for selecting elements with different states, or a particular element from a set of elements, but they are slower compared to other jQuery selectors. You should either find a way to replace the pseudo selector or be very specific in using it. Let’s take a look at examples of both. The following jQuery code selects all elements which are visible:

$(":visible");

You can be more specific here. Like,

$("input:visible");

or even better,

$("form").find("input:visible");

Pseudo selectors like :first, :last and :eq allow you to select a particular element from a set of elements. As an example, the following jQuery code will select the first table row using the :first pseudo selector.

$("tr:first")

The above code can be replaced with better performing code, but first you need to cache the selector (table row in this case).

var tRows=$('tr');

Since jQuery stores this as an array, we can take advantage of it. To get the first table row:

var firstRow=$(tRows[0]);

To get the last element (:last),

var lastRow = $(tRows[tRows.length - 1]);

Or to get any nth row (:eq(n)),

var nRow=$(tRows[n]);

Conclusion

jQuery is an awesome library that makes developers lives simple, but when not used properly it can be the stuff of nightmares! It’s important to write highly optimized and efficient code for better performance and scalability, on any application. This post shows how to write optimized code for jQuery selectors. These optimization tips show the importance of ID based selectors, the advantages of caching the selectors, defining a context to speed up DOM traversal, being very specific about the selector and using class & pseudo selectors wisely. Make a habit of following these tips to get the best performance from your code!

How to Increase Conversion Rates with Ouibounce

One surefire way to increase conversion rates on your landing pages is to include some sort of pop-up, be it one that appears as soon as your user visits the page, or an exit pop-up that appears when the user is going to leave the page (usually this type of pop-up is activated when the cursor hits a certain point of the viewport). While no user will tell you that they love pop-ups, there’s no denying that they work to get more people to engage with your site and your content.

An easy way to add pop-ups to your sites is by using the open source, lightweight, and totally free Ouibounce plugin. The plugin gives you total control over your modals, and lets you customize things like a timers, cookie names, cookie expiration time (so how long you want a cookie to last before it expires and a user is exposed to the pop-up again), and more. You can define sensitively, which applies to the exit pop-up option, because sensitivity allows you to choose how far the cursor can move up the the viewport before it triggers the modal to appear. If you don’t want to go the exit pop-up route, but you always don’t want your modal to appear immediately upon page load, there’s also a delay option that allows you to define how much time you would like to pass in between page load and the pop-up appearing.

Screen Shot 2017-03-25 at 10.15.54 AM

 

In terms of design, there are templates and suggestions provided by the plugin’s developer, but the style and content are totally customizable and up to you. Ouibounce gives you complete control of how you want your pop up to look and function within your project. The plugin is easy to install and almost even easier to use, and it will definitely give you great results if you’re looking for a lightweight, simple, and customizable pop-up plugin for any of your sites or pages.

Four free online Java compilers

Java codes are one of the most popular methods of developing software. Multiple online java code compilers are available which help to edit, compile and even publish so that designers don’t  have to open an IDE every time they need to get a job done. Here are some of the best online compilers available for designers.

1. JDoodle 

Developers who are working exclusively with codes written in one of the java languages will find Jdoodle Online Java Compiler and Editor an immense help. This compiler allows designers to check and compile as well as save the java codes in its online data base so that they don’t have to install or open a separate IDE for the same purpose. The site is developing continuously, taking care of the small niches so that developers will be able to use it even more smoothly. It is also working towards the addition of more and more libraries to the already existing vast database.

java-compilers

2. Ideone

In addition to compiling java code, ideone.com also allows users to debug the same with great ease and comfort. It also has a very useful customer support system that will help with any problems. It supports more than 60 languages and is super easy to use. All developers need to do is enter the java code they have written and the work will be done in no time. The latest Sphere Engine technology that has been launched by the site also helps to execute the written codes in remote servers with great ease. It also allows developers to check out sample codes so they can get an idea about how it works.

java-compilers

3. CodeTwist

CodeTwist’s promotional line states that it is a “simple C, C++ and java interpreter and compiler” and the site truly lives up to that credo. This is one of those online code compilers that allows developers to compile written codes with ease. The site is depicted as a simple single page with two boxes. Choose the language of the code that you want to compile, i.e. C, C++ or java and enter your code in the adjoining box and it will be compiled. It also allows developers to write any kind of input that may be required with the written code and it immediately provides the results.

java-compilers

4. Browxy

Although only in its beta stage, browxy.com allows developers to compile Java codes online for free. It is made for individual use and is not meant for commercial purposes. The users are given the freedom of compiling as well as executing written codes online. This site is developing at a rapid rate for providing customers with a better user interface and compiling for commercial use. It is pretty simple to use and provides the developers with fast results. It allows users to save their project making it easy to edit or add at a later date. Users can also download the results and get an URL for the same.

java-compilers

Setting up Visual Studio Intellisense for jQuery

In September 2008, at the jQuery Conference, it was announced that Microsoft would be shipping its upcoming releases of Visual Studio with jQuery built in. They would not fork or change the jQuery code but ship it as is. Microsoft also announced that they would distribute IntelliSense-annotated documentation JavaScript files for Visual Studio 2008 that developers can reference in their files to enable IntelliSense for jQuery. The following instructions will help you get started using this tool to make writing jQuery scripts faster than ever.

Read the rest of this entry »

Better, Stronger, Safer jQuerify Bookmarklet

A long time ago I built myself a little bookmarklet to load jQuery on pages that don’t already have it. The idea was to allow me to play around with any page on the web, using jQuery in the Firebug (and now Safari or IE8) console. I blogged about it, got lots of great feedback, and then blogged about an improved version. Now that a lot more great feedback has come through the comments of the updated bookmarklet post, I’ve decided to update it one more time.

Read the rest of this entry »

Updated jQuery Bookmarklet

For the most recent version of the bookmarklet, see the Better, Stronger, Safer jQuerify Bookmarklet entry.

About 1 1/2 years ago I put together a little “jQuerify” Bookmarklet (and blogged about it here). It’s a nice little tool that allows you to play around with jQuery on a page that doesn’t already have jQuery loaded and see the results immediately. Based on feedback from others, I’ve updated the bookmarklet a bit. Now, it first checks to see if jQuery is already loaded on the page and doesn’t bother loading it if it’s there. Also, instead of showing an alert message, it temporarily places an absolutely positioned div at the top of the page with a message saying either “This page is now jQuerified” or “This page was already jQuerified.” After 2 1/2 seconds, the message fades out and is removed from the DOM. Here is what the script looks like before it is converted to bookmarklet format (replacing spaces with %20, etc.):

Read the rest of this entry »