jQuery optimize selector performance
Best way
var $arms = $( "#container" ).find( "div.robotarm" );
or
var $arms = $( ".containers" ).find( "div.robotarms" );
or
var $radioButtons = $( ".category ).find( input:radio" );
Use ID selector with find().
Use tag.class if possible on your right-most selector, and just tag or just .class on the left.
Avoid Excessive Specificity. Better: Drop the middle if possible.
Avoid the Universal Selector *.
Append Outside of Loops
var myHtml = "";
$.each( myArray, function( i, item ) {
myHtml += "<li>" + item + "</li>";
});
$( "#ballers" ).html( myHtml );
Cache Length During Loops
var myLength = myArray.length;
for ( var i = 0; i < myLength; i++ ) {
// do stuff
}
Detach Elements to Work with Them.
The DOM is slow. Use detach() to remove an element from the DOM while you work with it.
var table = $( "#myTable" );
var parent = table.parent();
table.detach();
// ... add lots and lots of rows to table
parent.append( table );
Don’t Act on Absent Elements
// Bad: This runs three functions before it
// realizes there's nothing in the selection
$( "#nosuchthing" ).slideUp();
// Better:
var elem = $( "#nosuchthing" );
if ( elem.length ) {
elem.slideUp();
}
// Best: Add a doOnce plugin.
jQuery.fn.doOnce = function( func ) {
this.length && func.apply( this );
return this;
}
$( "li.cartitems" ).doOnce(function() {
// make it ajax!
});
Use Stylesheets for Changing CSS on Many Elements.
// Fine for up to 20 elements, slow after that:
$( "a.swedberg" ).css( "color", "#0769ad" );
// Much faster:
$( "<style type=\"text/css\">a.swedberg { color: #0769ad }</style>").appendTo( "head" );
Beware Anonymous Functions
// BAD
$( document ).ready(function() {
$( "#magic" ).click(function( event ) {
$( "#yayeffects" ).slideUp(function() {
// ...
});
});
$( "#happiness" ).load( url + " #unicorns", function() {
// ...
});
});
// BETTER
var PI = {
onReady: function() {
$( "#magic" ).click( PI.candyMtn );
$( "#happiness" ).load( PI.url + " #unicorns", PI.unicornCb );
},
candyMtn: function( event ) {
$( "#yayeffects" ).slideUp( PI.slideCb );
},
slideCb: function() { ... },
unicornCb: function() { ... }
};
$( document ).ready( PI.onReady );
Code Organization Concepts
// Using an object literal for a jQuery feature
var myFeature = {
init: function( settings ) {
myFeature.config = {
items: $( "#myFeature li" ),
container: $( "<div class='container'></div>" ),
urlBase: "/foo.php?item="
};
// Allow overriding the default config
$.extend( myFeature.config, settings );
myFeature.setup();
},
setup: function() {
myFeature.config.items
.each( myFeature.createContainer )
.click( myFeature.showItem );
},
createContainer: function() {
var item = $( this );
var container = myFeature.config.container
.clone()
.appendTo( item );
item.data( "container", container );
},
buildUrl: function() {
return myFeature.config.urlBase + myFeature.currentItem.attr( "id" );
},
showItem: function() {
myFeature.currentItem = $( this );
myFeature.getContent( myFeature.showContent );
},
getContent: function( callback ) {
var url = myFeature.buildUrl();
myFeature.currentItem.data( "container" ).load( url, callback );
},
showContent: function() {
myFeature.currentItem.data( "container" ).show();
myFeature.hideContent();
},
hideContent: function() {
myFeature.currentItem.siblings().each(function() {
$( this ).data( "container" ).hide();
});
}
};
$( document ).ready( myFeature.init );
The Module Pattern
// The module pattern
var feature = (function() {
// Private variables and functions
var privateThing = "secret";
var publicThing = "not secret";
var changePrivateThing = function() {
privateThing = "super secret";
};
var sayPrivateThing = function() {
console.log( privateThing );
changePrivateThing();
};
// Public API
return {
publicThing: publicThing,
sayPrivateThing: sayPrivateThing
};
})();
feature.publicThing; // "not secret"
// Logs "secret" and changes the value of privateThing
feature.sayPrivateThing();
// Using the module pattern for a jQuery feature
$( document ).ready(function() {
var feature = (function() {
var items = $( "#myFeature li" );
var container = $( "<div class='container'></div>" );
var currentItem = null;
var urlBase = "/foo.php?item=";
var createContainer = function() {
var item = $( this );
var _container = container.clone().appendTo( item );
item.data( "container", _container );
};
var buildUrl = function() {
return urlBase + currentItem.attr( "id" );
};
var showItem = function() {
currentItem = $( this );
getContent( showContent );
};
var showItemByIndex = function( idx ) {
$.proxy( showItem, items.get( idx ) );
};
var getContent = function( callback ) {
currentItem.data( "container" ).load( buildUrl(), callback );
};
var showContent = function() {
currentItem.data( "container" ).show();
hideContent();
};
var hideContent = function() {
currentItem.siblings().each(function() {
$( this ).data( "container" ).hide();
});
};
items.each( createContainer ).click( showItem );
return {
showItemByIndex: showItemByIndex
};
})();
feature.showItemByIndex( 0 );
});
jQuery plugins
$.fn.greenify = function() {
this.css( "color", "green" );
return this;
}
$( "a" ).greenify().addClass( "greenified" ); // Makes all the links green.
// Protecting the $ Alias and Adding Scope
(function( $ ) {
$.fn.showLinkLocation = function() {
this.filter( "a" ).each(function() {
var link = $( this );
link.append( " (" + link.attr( "href" ) + ")" );
});
return this;
};
}( jQuery ));
// Usage example:
$( "a" ).showLinkLocation();
Комментариев нет:
Отправить комментарий