jQuery Shortcuts - a Few of the Best - ByteScout
  • Home
  • /
  • Blog
  • /
  • jQuery Shortcuts – a Few of the Best

jQuery Shortcuts – a Few of the Best

This article was written on June 26, 2017, and updated in January 2021

It’s said that necessity is the mother of invention – and the emergence of jQuery in the world of web development is a great example of this. The majority of JavaScript’s libraries were rolled out to improve the productivity and performance of web systems. Developers were having a hard time dealing with compatibility issues between JavaScript and browser APIs in various web browsers, and jQuery emerged as a solution to this problem: an environment that enabled developers to smooth off the compatibility issues they faced and create code that worked for (almost) everyone.

  1. Working with DOM in a Loop
  2. Why use Classes, when we have IDs?
  3. The Return of the ‘False’!
  4. Determining Browser
  5. Selecting Random Element
  6. Determining Page Weight

jQuery is continuously developing and progressing with time. If this nimble and feature-rich JavaScript library is one of your major tools, then we hope you’ll find the following three workflow shortcuts very useful to boost the performance of your web applications.

Working with DOM in a Loop

One of jQuery’s best features is that it is able to manipulate the DOM by using a very small amount of code – it’s very easy to change things, and developers don’t even need to think about what is going on behind the curtains. The following code shows a good example of appending nodes to an object named myDiv

var myDiv = $('#emailList');
for (var a = 0; a < 100; a++) {
myDiv.append('<div>' + a + '</div>');
}

We already know that this is a standard way to attach the nodes to the given parent. However, it is not an optimal approach, because jQuery has to continuously perform DOM operations within the loop. As the number of loop iterations increases, performance gets weaker. If you want to have a high-performing algorithm that doesn’t compromise performance, you can opt for a more optimal solution to fix the child nodes. Like this:

var myDiv = $('#emailList');
var resdiv = '';
for (var a = 0; a < 100; a++) {
resdiv += '<div>' + a + '</div>';
}
myDiv.html(resdiv);

This code contacts the DOM only once after our loop has finished working. This leads to better performance and efficient functioning of the script.

Why use Classes, when we have IDs?

Most of the jQuery fans among you will already know that jQuery uses the browser’s native method, getElementByID() in order to get objects. However, when it comes to checking performance metrics, it can be more convenient to use a more complex selector, write your own elector, or even define a container for the element which needs to be selected:

//This example simply creates a list, fills it with elements and selects each element only once
console.time('class');
var mylist = $('#list');
var elements = '<ul>';
for (a=0; a<1000; a++) {
    elements += '<li class="item' + a + '">item</li>';
}
elements += '</ul>';
mylist.html (elements);
for (a=0; a<1000; a++) {
    var s = $('.item' + i);
}
console.timeEnd('class');
console.time('id');
var mylist = $('#list');
var elements = '<ul>';
for a=0; a<1000; a++) {
    elements += '<li id="item' + a + '">item</li>';
}
 elements+= '</ul>';
list.html (elements);
 for (a=0; a<1000; a++) {
    var selection = $('#item' + a);
}
console.timeEnd('id');

This code shows the differences between the two ways of fetching and selecting the elements, describing an unlimited over-time (around 5 seconds) to load the class drive code.

The Return of the ‘False’!

Dealing with longer pages can be a pain when functions are developed without any “false” return statement. Remember that it’s always viable to use false whenever you use functions so that your browser doesn’t take you to the top of your webpage:

//This is your function without any return statement
$('#item').click (function () {
   // add your code here
});
//This is how you should write your function i.e. setting the return statement to false
$('#item').click (function () {
   // add your code here
   return false;
});

Determining Browser

Another interesting way you can use jQuery is to use it for detecting browser. The web has evolved over the past few years, and you will find a lot of web browsers out there. You can use jQuery to detect browsers easily. All you need to use it the following code to detect the browser.

$(document).ready(function()) {
    // In case the browser is chrome
    if ($.browser.chrome) {
        // do this
    }
    if ($.browser.Mozilla & $.browser.version >= "5.3") {
        //do this
    }
    //and so on
}

Selecting Random Element

You can also use jQuery to create functions based only on your needs. For instance, you can create a random element function which returns the random class in the document to the caller function. This can be used to animate the page or even in other useful situations. To do so, we can create a new function of $.expr[‘:’ ].

Below is the code that utilizes random functionality.

(function($){
    var random = 0;
    $.expr[':'].random = function(x, y, z, c) {
        if (i == 0) {
            random = Math.floor(Math.random() * r.length);
        }
        return i == random;
    };
})(jQuery);

// This is how you use it:
$('li:random').addClass('less');

Determining Page Weight

There is another clean trick that you can use when coding with jQuery. You can use jQuery to determine the page weight which can be done with a single line of code.

It is a well-known fact that the page weight determines how fast or slow it loads. You can quickly check out how long it takes for the page to load. To do so, you need to type the following command in the console.

//Check if page weight
console.log($(*).length)

So, the lower times mean that the site will load faster. This way you can find out what is hampering the site’s loading time and then take steps based on it.

Of course, these are only some recommended shortcuts. Other options we’ll look at in the future include using a CDN (Content Delivery Network) and loading your jQuery script from a regional server. If you’d like to discuss these more, and how we apply them in our work, contact us!

   

About the Author

ByteScout Team ByteScout Team of Writers ByteScout has a team of professional writers proficient in different technical topics. We select the best writers to cover interesting and trending topics for our readers. We love developers and we hope our articles help you learn about programming and programmers.  
prev
next