DEV Community

Cover image for Ultimate Jquery Speed enhacements for your website
Uriel Bitton
Uriel Bitton

Posted on • Edited on

Ultimate Jquery Speed enhacements for your website

The DOM can get pretty slow quickly, especially if it becomes large. When we start accessing and manipulating elements within deep children of the DOM tree, these actions become extremely expensive, resulting in slow processing and loading speeds of your website or web app.

Fortunately there exists a few really good optimizing techniques to speed up the manipulation of the DOM considerably, making a noticeable speed up of your website when used properly. Let's get to it.

  1. Caching selectors

Caching selectors can improve the DOM speed as it caches your selectors in memory instead of accessing its contents deep inside the DOM tree.
Here's how we can achieve selector caching:

var mydiv = $('.mydiv');
Enter fullscreen mode Exit fullscreen mode

Simple yet powerful.

  1. Using stylesheets for changing CSS for many elements

Jquery documents that if you're changing up to 20 element's styles, it can damage your page speed a lot. instead there's a nifty technique that will result in a 60% speed increase.

//if we have more than 20 elements that have the class 'box'
$('.box').css('color','red'); //this will be slow
//instead we append a style tag with the desired properties for that class
$( "<style type=\"text/css\">.box { color: red}</style>").appendTo('head');
Enter fullscreen mode Exit fullscreen mode

Pretty neat, huh?

  1. Optimizing Selectors Since accessing and manipulating selectors can get really expensive, there are some cool and very simple tricks:
$('.box > *'); //this can become very expensive
//instead use .children method
$('.box').children(); //much faster

//use .find instead of selector "finding"
$('.box p'); //slow
$('.box').find('p'); //fast

//avoid selector specifying
$('.box.container .text span'); //slow
$('.box span'); //better
Enter fullscreen mode Exit fullscreen mode
  1. Detach elements when working complex processes

I can't stress this enough, the DOM is slow, we constantly need to optmize it. When we are processing a large element inthe DOM, we can detach that element while we work on it

var box = $('.box');
var tempbox = box.parent();
tempbox.detach(); //detach the element from the DOM 
// add a ton of elements here...
tempbox.append(box); //re-attach or append the element to the box element
Enter fullscreen mode Exit fullscreen mode

A powerful yet not too complicated technqiue

Conclusion
With these techniques we can considerably optimize the DOM speed of our web page. These are very usable and the opportunities come up very often, so take advantage of them and enjoy.

Like always, see you in the next post!

Uriel Bitton
Website: www.flexrweb.com
Email: info@flexrweb.com

Top comments (0)