Blog About Me Posts By Tags Subscribe Elastic Search My Sessions Terraform

Pavan Kumar Aryasomayajulu


Jquery optimization tip

Sometime we write code using Jquery Custom selector to great extent. It works fine with pages that has less amount of data but when the page size is growing I am getting an error in ie (Unresponsive script error).

These are the few things that I did to overcome these kind of messages

Lesson learnt

In my opinion using the jquery selector something like this
$(‘[customAttribute=someValue]’) should be avoided when the dom is huge.

Reason: This selector searches entire dom content to find the element that has attribute “customAttribute” with value “someValue”. This will be a performance hit if the page content is huge.

Tip: If you want to make use of Jquery selectors it would be nice if we can cache it using some java script values.
For example :

$('[customttribute=someValue]');
$('[customttribute=someValue]').css('border','3px dotted green')
$('[customttribute=someValue]').parent();



Here we are adding some css and also trying to get parent element of $(‘[customttribute=someValue]’)

So what happens here is in the above code it will loop on entire pages dom elements twice to find the element and then it applies the css and to find parent element.

So to optimize this we can do something like this.

var domElement=$('[customttribute=someValue]');
domElement.css('border','3px dotted green');
domElement.parent();


So we are doing the same task here but the only difference is we are caching the selector result into js variable . So it loops only once on entire page’s dom to get the required element and then apply css and find parent.
This has really a great impact on my code

Keywords: Jquery, Jquery Optimization



Thanks, Pavan

#Jquery