blog

CUT DOWN ON GLOBAL VARS BY USING JQUERY TO QUERY THE DOM

July 07 2010 by Joseph Smith

After writing some proof of concept code and showing it to a co-worker a while back, it was pointed out to me that I was not using Javascript (specifically jQuery) to query the DOM. I was going down weird roads that, as a developer, should have set my Spidey-sense tingling. Things like

var firstRun = false;
 
if(!firstRun){
   ...some code involving DOM manipulation
  firstRun = true;
}

If you are manipulating the DOM using JS, you should query the DOM to determine what the next action is you want to take.

Don't go eating memory (and a perfectly good namespace) with vars if you don't need them. Especially when there is a better way... This is what tools like jQuery are exceedingly good at.

one option if you are appending data to the DOM is to... check the status of the DOM

if($('#some-div').children().length == 0){
   ...some code inserting elements
}

The use case will often be different than this, but the the lesson here, for me at least is... Pay attention to your tools and use them to your advantage.

Joseph Smith

Joseph Smith

Joseph currently works full-time as a developer for Legwork Studio in Downtown Denver, CO.

In his past life, he was a touring musician and turned screws on/repaired Apple hardware.

Tags