Quantcast
Channel: Jquery | Matthew Hailwood » Matthew Hailwood
Viewing all articles
Browse latest Browse all 6

#1 Crime of jQuery – DOM Abuse

$
0
0

The Crime

Here is an example,

$(function(){
  $('#id').change(function(){
    //do stuff
  });

  $('#id').css('border-color', '#ff0000');
  var val = $('#id').val();
});

See what is happening here?
There are several calls to $(‘#id’).

The reasoning

Why is this so bad?
Well, imagine the DOM as a giant pool of all elements on your page, every time you call $(‘#id’) you are diving into the pool and swimming around until you find the element you need. That adds some serious overhead on every call!

The solution

Caching!

$(function(){
  var element = $('#id'); //see what we are doing!
  element.change(function(){
    //do stuff
  });

  element.css('border-color', '#ff0000');
  var val = element.val();
});

See what we have done here?
We cut down our diving to only one call, keeping with the fish analogy think of it as, after storing the selector we now have it on a fishing rod, every time we want it we simply reel in the line and have our element!

Actually, There is one more thing we can do to improve this, method chaining!

$(function(){
  var element = $('#id'); //see what we are doing!
  element.change(function(){
    //do stuff
  }).css('border-color', '#ff0000');
  var val = element.val();
});

Well, hopefully after reading this post you will no longer commit this crime, and pass this message along to anyone you know that commits this crime!


Viewing all articles
Browse latest Browse all 6

Trending Articles