Jquery optimization tip
Recently i wrote some code that makes use of Jquery Custom selector to great extent. It is working fine with page that has less amount of data but when the page size is growing i am getting an error in ie stating(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 i 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.
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 :
So here we are adding some css and also trying to get parent element to our $(‘[customttribute=someValue]’)
So what happens here is in the above lines 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
Pavan Kumar Aryasomayajulu ,