I’ve collated a short list of useful tips that I’ve picked up from various sources since I started working with jQuery. This is by no means an exhaustive list, just some tips that I’ve found invaluable when it comes to jQuery development.
For those of you who haven’t heard of jQuery it’s gained a lot of popularity over the last few years for making the following tasks incredibly simpler:
- Cross-browser support
- DOM manipulation
- AJAX development
So here goes:
- Use the ready() function rather than the <body> onload event handler – the obvious tip 🙂
- Utilise your browser’s developer toolbar – I prefer IE for development so I’ve used it as an example:
- A “Script” tab which comes in for debugging, stepping into code, watching etc.
- A “Profiler” tab which analyses the execution time of Functions and Call Trees – very handy if you want to optimise your code
- DOM manipulation is expensive so if you need to execute a change against the DOM first prepare it then execute it, don’t keep firing updates at the DOM as you’ll suffer avoidable delays
- Use chaining where ever possible, i.e. this is good
$("p").css("background", "yellow").css("font-style", "italic");
where as this is bad:
$("p").css("background", "yellow"); $("p").css("font-style", "italic");
- If you’re going to implement a jQuery plugin, i.e. jQuery UI that has been developed externally always be mindful of the following:
- Will you be keeping abridged of plugins latest releases?
- Will you be able to test how future jQuery library releases impact on the current version of the plugin you’re running?
- Is there a reasonable forum available for Q&A in the event you run into an issue? Don’t underestimate this last one, people who have experienced similar issues as I when using a plugin have saved me an enormous amount of time by posting a solution on the plugin’s forum
- Invest time learning the selectors – the selectors will allow you to write what typically takes you several lines of code in a few characters
If you want some more tips, because I’ve only detailed a few and don’t want to leave you short-handed, then head over to these websites:
- Improve Your jQuery – 25 Excellent Tips
- 15 Powerful jQuery Tips and Tricks for Developers
- 30 Pro jQuery Tips, Tricks and Strategies