Stop using jQuery!! (all the time…)

I apologize for the link bait. I feel bad doing it. But – at least you know I’m not a slimy SEO person and there is something useful in this article. ;)

Yesterday I blogged a simple little POC (Proof of Concept) that demonstrated adding a class to a random list element. As I said in the post yesterday, this was rather trivial code, but I wanted to share it because of the use of LocalStorage.

About an hour or so after I posted it, something began to bug me. I opened up the template and looked at the Network requests in Chrome dev tools.

Just in case it isn’t obvious, let me break it down for you. My HTML document was a bit over 1.5K. The jQuery library, compressed, was 33K. To be fair, my HTML was limited to what was required for the demo, but even if I increased the size of my document ten fold, it would still be less than the size of the jQuery library.

Don’t get me wrong. I love jQuery. I love what it has done for my development, my career, and my skin care. (Um, ok.) That being said, you don’t need jQuery as much as you think. Consider what my demo did:

  • Run a function when the DOM was loaded.
  • Find some DOM items via CSS selectors.
  • Remove a class from one thing, add it to another.

That’s it. Surely I could do that without an entire library, right? First, I switched to listening for the DOMContentLoaded event.

For finding DOM items, I made use of querySelector and querySelectorAll.

For adding and removing classes, I made use of the classList property.

After these changes, the size of my application was pretty much next to nothing.

Here is the complete template. Any questions?