Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery pitfalls to avoid [closed]

People also ask

Why jQuery is not recommended?

Back to the topic at hand on Why You shouldn't use JQuery in a framework? Because it'll just make your app heavy. Everything JQuery can do, VanillaJS/JS/TypeScript can do better and faster. It results to a terribly large amount of JavaScript code written.

Should jQuery be in head or body?

It is actually best practice to load jQuery at the very end of the body element. This way all of your images load before jQuery.

Is jQuery getting deprecated?

The team announced that the cross-platform jQuery Mobile project under its umbrella will be fully deprecated as of October 7, 2021. New technologies for mobile app development have evolved since this project was launched in 2010, so we're encouraging developers to plan for this jQuery Mobile transition.


Being unaware of the performance hit and overusing selectors instead of assigning them to local variables. For example:-

$('#button').click(function() {
    $('#label').method();
    $('#label').method2();
    $('#label').css('background-color', 'red');
});

Rather than:-

$('#button').click(function() {
    var $label = $('#label');
    $label.method();
    $label.method2();
    $label.css('background-color', 'red');
});

Or even better with chaining:-

$('#button').click(function() {
    $("#label").method().method2().css("background-color", "red"); 
});

I found this the enlightening moment when I realized how the call stacks work.

Edit: incorporated suggestions in comments.


Understand how to use context. Normally, a jQuery selector will search the whole doc:

// This will search whole doc for elements with class myClass
$('.myClass');

But you can speed things up by searching within a context:

var ct = $('#myContainer');
// This will search for elements with class myClass within the myContainer child elements
$('.myClass', ct);

Don't use bare class selectors, like this:

$('.button').click(function() { /* do something */ });

This will end up looking at every single element to see if it has a class of "button".

Instead, you can help it out, like:

$('span.button').click(function() { /* do something */ });
$('#userform .button').click(function() { /* do something */ });

I learned this last year from Rebecca Murphy's blog

Update - This answer was given over 2 years ago and is not correct for the current version of jQuery. One of the comments includes a test to prove this. There is also an updated version of the test that includes the version of jQuery at the time of this answer.


Try to split out anonymous functions so you can reuse them.

//Avoid
$('#div').click( function(){
   //do something
});

//Do do
function divClickFn (){
   //do something    
}

$('#div').click( divClickFn );