13

I have a project coming up to build an interface which allows a user to construct content with pre-defined templates and code snippets.

We've already decided to use the jQuery and jQuery UI frameworks to help us with the dragging/dropping/sorting parts. There also needs to be some edit-in-place, and I'm going to use contenteditable combined with jQuery's CSS functions.

I already have quite a bit of experience with both frameworks (and love them), but my typical project so far has run to about 50 lines whereas this one will run to a lot more than that, using more of the functions and writing my own plugins.

Before I start work on the project I'm wondering if there are any common pitfalls with jQuery - kind of like 'jQuery - the Bad Parts'. Are there functions that are just best avoided? Are there functions which need working around?

I read this link but it's now 2 years old and a lot has changed in jQuery (and browsers) since then.

Any 'Use this framework instead' or 'Don't use a framework' answers will be ignored - I have to use jQuery. Any 'jQuery is rubbish' rants that don't provide solutions will also be ignored. Constructive comments only please. If I knew how to do better in JavaScript what jQuery does, I wouldn't be using jQuery.

10
  • @Blowski: I haven't voted to close this, but I have a feeling others might (for being too subjective). Unfortunately, this could end up being grounds for a religious debate. Commented Apr 30, 2011 at 0:59
  • @Andrew I was worried about that too, hence the footnote. I had a look around Google for jQuery criticisms but couldn't find anything constructive or up-to-date. I've tried to make it as specific as possible, and if it does turn into a religious war-ground I'll delete the question myself anyway.
    – Dan Blows
    Commented Apr 30, 2011 at 1:01
  • 1
    As you pointed out, the linked diatribe isn't relevant because it's 2 years old. Keep your finger on the pulse of the API on forums and via the bug tracker bugs.jquery.com jQuery's biggest problems will change as the library gets debugged, new updates and features are released, and new issues are introduced. This question will always have shifting answers over time. Answers will become subjective when some people consider something a certain classification of a problem (e.g. annoyance in jQuery) whereas others welcome the same item as a feature, etc.
    – John K
    Commented Apr 30, 2011 at 3:42
  • 1
    This is still not constructive: it's a hidden features question in disguise. How is this answerable? List every possible "important challenge" (what does that even mean?) and its workaround?
    – user113292
    Commented Apr 30, 2011 at 4:20
  • 4
    @Mark: Well, you won't let it onto Programmers, so it has no place to go. Once in a while, someone asks an interesting subjective programming question; this is one of them. Since it's squarely programming-related, I'm inclined to give it a pass; if it gets closed again, I'll let it stand. Commented Apr 30, 2011 at 4:22

7 Answers 7

8
+100

I'll answer half of your question. Here's a laundry list of pitfalls based on painful experience, not all of which I have solutions to.

  • The temptation to make heavy use of long chains of selectors ("ul#leftnav li p a.current ") makes your code brittle. It may FEEL clever ("Hey, I'm teh CSS master!"), but it breaks easily when layout changes in any non-trivial way.
  • Using the DOM as the database. It seems like a neat idea to use .data() to attach data to your DOM elements, to track your page state, and to link DOM elements together, but if you go overboard, you start to lose track of what's where.
  • Putting way too much stuff in $(document).ready(). Once again, it's natural to initialize all your events and data here, but you soon run into organizational and ordering problems. Look into MVC-like solutions to keep things organized.
  • Not quite cross-browser. Test in all targeted browsers early and often! jQuery, although a wonderful abstraction, is still a leaky one. Events and attributes don't always behave exactly the same in different JS engines.
3
  • Thanks for that. The third one is my big concern. I am always confused about what goes in $(document).ready() and what goes outside. The way the documentation is written it suggests everything has to go inside there, which isn't helpful. Re: x-browser bugs - any particularly egregious ones you are aware of?
    – Dan Blows
    Commented Apr 30, 2011 at 1:18
  • @Blowski - Kinda bummed that this question got closed. Regarding .ready(), it's never been a matter of outside vs in, but rather a matter of organization. Where do you put event handlers vs the functions that do AJAX calls vs the functions that receive AJAX callbacks? Again, I would suggest an MVC-type approach to help. It might not be a cure, but it helps organize your code.
    – anon
    Commented Apr 30, 2011 at 3:43
  • yay, since it's been reopened, I've unchosen your answer to encourage some more feedback. Thanks for your support in getting reopened :)
    – Dan Blows
    Commented Apr 30, 2011 at 4:36
5

Keep the glue minimal

Things I've done in jQuery that I've learned to avoid:

  • Overusing big, clever plugins. Keep it simple or keep it out.
  • Big, complex files. Keep files small and descriptive.
  • Polluting the global namespace. Use closures per file. Export into a namespace.
  • Constructing markup with $(). Template using backbone / mustache to keep js clean.
  • Brittle CSS selectors. Select by ID where possible, using hierarchy causes problems.

Keep it maintainable

Things I've done in jQuery that I've learned to do every time:

  • Definitely make use of automated testing. Maintains code structure and peace of mind.
  • Keep state information out of the DOM, in a model.
  • Choose storing callback functions and referring to them by var name over crazy function nesting.
  • Make use of a minimal framework to establish conventions early.

That last one is a must. There are countless ways of organising the JS side of a project. Choose something like ember.js to give you a set of conventions, then stick to them!

4

One of the most important challenges, whether or not the project uses jQuery, is code organization.

With jQuery, it's very easy to write code like this:

$.get('/data', function (data) {
    // process data, then
    alertThing.fadeIn(function () {
        // when the alert is visible, handle clicks
        alertButton.click(function () {
            // the user confirmed, so post
            $.post('/data', function () {
                // ... and on and on
            });
        });
    });
});

You end up with long chains and/or deeply nested functions that are hard to read and debug. Using Deferred objects can help, but it would be better to split your app into loosely coupled components. You can even package reusable (presentation, DOM-related) code into plugins.

jQuery's strength is cross-browser DOM manipulation; when it comes to organizing program / business logic, jQuery isn't the right tool. (Storing non-presentation data on the DOM is basically a crutch for this.)

Frameworks like Backbone or JavaScriptMVC help by providing structure for your code. It's "yet another framework to learn" but without it you end up writing your own MVC-like code anyway.

1

One of the biggest pitfalls is IE6. I find myself constantly having to make work arounds to make the jqueryUI stuff work in IE6 and forget about trying to make it work in IE 5.5

4
  • What functions don't work in IE6? We have discussed not supporting IE6, at least in the first version, although that was more because we didn't want to spend half the project coding for IE6 CSS. If jQuery UI has problems with IE6 as well, I suspect we will just drop IE6 support.
    – Dan Blows
    Commented Apr 30, 2011 at 1:00
  • One common work around is with the modal window things. For example in IE6 the modal window doesn't grow when content is dynamically added as well as if you have a drop down behind the modal window you have to include the bgiFrame.js file or else the Z-index is messed up
    – Avitus
    Commented Apr 30, 2011 at 1:02
  • bgiFrame is a plugin right? I had planned on using the modal functionality a bit, so that's good to know.
    – Dan Blows
    Commented Apr 30, 2011 at 1:04
  • Yes it is a plug in that help with the z-index issues of IE6 docs.jquery.com/Plugins/bgiframe
    – Avitus
    Commented Apr 30, 2011 at 1:06
1

Well I am a N00B but most of the problems I faced with Jquery' functions not working was in $("div > label") type of functions. Some times it would plain not work in IE( i guess 7) and I would have to explicitly specify it. Also the Document.Ready function wont work for me when i had loads of scripts loading in IE7. Overall Even though the above things might have been due to error on my part I find it best to avoid using ELE.children("#id") instead prefer ELE.find(".class") as this will give u a bit of flexibility over the layout and Because u will be doing loads of things on similiar elements(ex. copy multiple divs) My only suggestions would be to use Classes instead of IDs and use Find instead of Children. What i am trying to say here is if u use Find instead of children atleast u gain independence from change in layout of individual element as long as they are in distinct containers.(hope this is useful)

4
  • 1
    ELE.children("#id") is pointless, mate. Just use $('#id'); It'll be faster anyway. Commented May 4, 2011 at 17:50
  • thats right @Levi but some times in case of duplicate ids it helps Commented May 5, 2011 at 3:32
  • 2
    @Archan If you have duplicate IDs then you are doing it wrong. IDs are by definition supposed to be unique.
    – Chad
    Commented May 5, 2011 at 20:03
  • @Chad yup thats the case but the duplicate iDs are forgiven in chrome and firefox and the designer i work with usually keeps her css fixed to ids. Commented May 6, 2011 at 3:44
0

One bad-practice trap to avoid is doing lots of HTML generation from within your javascript. For example, I see stuff like this a lot:

$('<a href="'+url+'">'+text+'</a>').appendTo('#container');

Beware! 90% of the time this kind of code is generating similar markup to that which is already coming from the server. In other words, as soon as the markup for your links change you'll to have to hunt down the line of javascript and update that as well.

I highly recommend using the official jQuery templates plug-in as soon as you feel that first urge to generate HTML in your javascript!

2
  • Have you used the JavaScriptMVC framework? That has a template mechanism, but I haven't used it so far because of the need to learn yet another framework.
    – Dan Blows
    Commented May 3, 2011 at 23:44
  • I haven't used JavascriptMVC. jQuery templates aren't the only solution but they work very well. Mustache.js is another one to check out since there are mustache interpreters written for almost every popular web development language. I only recommended jQuery templates since it eliminates the need to 'learn another framework' Commented May 4, 2011 at 1:24
0

I've personally worked a lot with jQuery and what I can say is the problems you will face are not with jQuery but with the nature of javascript itself. You need to keep your code organized and well documented. Try following some kind of mvc (backbonejs, javascript mvc or something of the kind). AVOID GLOBAL VARIABLES. Use namespaces for what ever objects you utilize. Use the document.ready for as few events as possible. Otherwise you are going to over pollut it and again... it becomes messy.

Keep a javascript nature of things as in using closures, objects and methods.

Careful of over appending strings into the dom. Make sure you are using .load() or .clone() to get html from your template file. If you use backbone or javascriptmvc this will come inherently.

Hope this helps and good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.