Am I Using Too Much Jquery? When am I Crossing the Line

Am I using too much jQuery? When am I crossing the line?

You're crossing the line if you're using jQuery to do things that can be done easily without jQuery. jQuery's purpose is to make life easier, but it shouldn't be at the expense of compatibility or usability.

jQuery most certainly shouldn't be used as a replacement for CSS -- think of the users who have JavaScript disabled.

I know this image is overused, but someone had to throw it in here:
Sample Image

Image Credit - bobince.

jQuery append is taking too much time when repeated 500 times

I believe this to be a better solution

$.getJSON( "https://domain.ltd/parse_data.php", function( data_recieved ) {
if (data_recieved.length) {
var spns = '';
$.each(data_recieved, function(index, element) {
spns+='<span>' + element.name + ' = ' + element.amount + '</span><br />';
});
$( ".items" ).append(spns); // or use .html();
}
})

It seems like your DOM tree is deep & $( ".items" ) inside the loop is getting expensive.

When is it acceptable to use jQuery?

If I ever need to do anything past document.getElementById() in my web app, I always use jQuery.

I honestly find most of your con arguments against jQuery pretty weak, particularly the last one:

Even the simplest of tasks can perform poorly, because of the inherent complexity of the framework.

Do not agree with that at all. jQuery is incredibly simple while powerful and that's what I love about it.

How many lines of code will be saved using JQuery instead of straight JavaScript?

To attach a click handler using standard javascript, you might try something like this:

var myelement = document.getElementById("clickme");
function myClickHandler (evt) {
var evt = evt || event; // ie uses a global instead of
// passing an object as a param
(evt.target || evt.srcElement).style.width="110px";

}
if (myelement.addEventListener) {
myelement.addEventListener("click", myClickHandler, false);
} else if(myelement.attachEvent) {
myelement.attachEvent("onclick", myClickHandler);
} else if(typeof myelement.onclick === "function") {
(function () {
var oldfunc = myelement.onclick;
myelement.onclick = function (evt) {
var evt = evt || event;
oldfunc(evt);
myClickHandler(evt);
}
})()
} else {
myelement.onclick = myClickHandler;
}

or try to do something similar using jquery

jQuery("#clickme").click(function(evt){ jQuery(evt.target).css("width",110); });

You could argue that the first example code is a stupid thing to write every time you want to assign a click handler. Why not refactor that out into its own standard function, and reuse that? then you have a central function you can debug without having to rewrite every single instance once you've found something wrong.

This would be a very good argument, and that's exactly the point of a library like jquery. You save time by not writing this verbose boilerplate that's absolutely necessary if you want your code to work cross browser. You save time by not having to debug it. You save time by- if you do have to debug it, you just have to patch one function in jquery and file a bug report for the next version. If there's something wrong with the event binding code, then it's just one guy that has to change one bit of code, rather than thousands of people that need to change millions of bits of code. And when someone points out that you should test addEventListener first, the point becomes moot, because jQuery already does the established "correct" thing. And if it doesn't, it will in the next version.

jQuery won't help you on the really difficult domain specific problems, but for grinding through every day dom manipulations, it's better to use a library function than trying to wing it "close to the metal". There's too many cross browser splinters sticking out, and too many dumb verbose dom APIS, and it's too stupid to solve problems that have already been solved, over and over again.

You need SOME kind of library (not necessarily jquery) just to stay sane.

Now how much time and effort do you save, exactly? Who knows? it's immeasurable. How many times do you have to bind an event handler? How many times do you have to do any of the other things that jQuery provides in a simple function? One is strongly dependent on the other.

If you ever find a way to measure programmer productivity, do let us know, though. I think we'd all be very interested. In any case, we know from these objective facts, and our own personal subjective experiences that it's probably quite a substantial amount of time.

too much recursion error in jquery

You can use live or delegate to add listeners for elements that are created later:

$("a.cross-link").live("click", function()
{
$('a[href=#2]').trigger('click');
window.location.hash = "#2";
});

However, click does not trigger the default event of going to the URL, so you need to do that manually.

I've learned jQuery, should I go back and learn proper javascript ?

No.

The move to frameworks is driven by years of frustration over the browser-dependencies and sheer dislike for many of the original decisions made in the design of Javascript. Note that you are still working in Javascript though so it isn't really fair to say "learn Javascript" so much as "explore the areas of Javascript now handled by JQuery."

With respect to your attractiveness to a prospective employer, I'm pretty certain that JQuery would be a better skill to list on a resume than Javascript (I know it would in our shop). If you think about it, employers who care enough to do good client-side development will expect prospective employees to have experience with tools like JQuery. Those who don't care as much about client-side development simply won't make client-side skills - including Javascript - a priority. Indeed, if you are going to spend your time learning more about the client side, I'd recommend learning another client-side framework (e.g. YUI or Ext). Not only will it make you more valuable, it will almost certainly require a certain degree of exposure to more of Javascript's idioms due to differences in the frameworks.

Update - Rohan makes a good point about learning Javascript: that it may help you code more efficiently and effectively in JQuery. I agree in the abstract but I would personally be a bit hesitant to put too much effort in this area. As a long (long) time developer, I've learned to be very focused on the payoff from investments of time and effort. There is much to learn in the world, and only so much time to learn it. The time I spent learning how to write ISAPI dlls, for example, has paid very little compared to the investment.

Update 2 - A few people are making the argument that JQuery is slower than raw Javascript. Is anything ever new? This same argument about "raw" development versus frameworks has been going on for decades!

In this case it is especially perplexing, though. In my experience, people who adopt a client-side framework actually end up delivering client-side functionality. Those that don't tend to get locked into server-side solutions because of the inherent difficulty of handling DOM incompatibilities across browsers, Javascript idiosyncrasies, etc. Thus, recommending Javascript "for speed" misses the whole dynamic where a pure Javascript site is very likely to be slower because developers end up falling back on Server-side code just to stay productive.

New to javascript, why is jQuery such a beast?

The strange symbols you refer to are mostly CSS selectors, the standard way to address elements on the web. jQuery could've come up with its own conventions, but decided to go with what was standard and best known.

jQuery itself is surprisingly consistent. Once you wrap your head around the jQuery style you barely have to consult the documentation; things just work as you'd think they should.

The jQuery documentation is actually quite good and includes an example with every command. It also has a large user base, so a quick search will generally answer any questions you have. Google is your friend.

I'm guessing the issue is not jQuery, but a difference in javascript style compared to languages you're more familiar with. Watch Crockford's "Javascript: The Good Parts" for a reasonable introduction to good javascript style.

http://video.yahoo.com/watch/630959/2974197

Also check out Dustin Diaz's posts, I found his early screencasts where he'd build an app and talk about what he was doing very educational:

http://www.dustindiaz.com/

More than 5 items per line in jQuery Mobile navbar

Using jQuery mobile 1.4.0, all I had to do is to create my own CSS class:

.mytab {
width: 12.5% !important; /* 12.5% for 8 tabs wide */
clear: none !important; /* Prevent line break caused by ui-block-a */
}

..and include it in my list:

<ul id='tabsList'>
<li class="mytab"><a href="#tab1" data-ajax="false">One</a></li>
<li class="mytab"><a href="#tab2" data-ajax="false">Two</a></li>
<li class="mytab"><a href="#tab3" data-ajax="false">Three</a></li>
<li class="mytab"><a href="#tab4" data-ajax="false">Four</a></li>
<li class="mytab"><a href="#tab5" data-ajax="false">Five</a></li>
<li class="mytab"><a href="#tab6" data-ajax="false">Six</a></li>
<li class="mytab"><a href="#tab7" data-ajax="false">Seven</a></li>
<li class="mytab"><a href="#tab8" data-ajax="false">Eight</a></li>
</ul>

(original answer had jQuery mobile version wrong)

How do you step through jQuery code efficiently?

Tools

I'm using Firebug to debug jQuery code with some extensions for jQuery debugging:

  • FireQuery

FireQuery is a Firefox extension integrated with Firebug

  • jQuery expressions are intelligently presented in Firebug Console and DOM inspector
  • attached jQuery data are first class citizens
  • elements in jQuery collections are highlighted on hover
  • jQuerify: enables you to inject jQuery into any web page
  • jQuery Lint: enables you to automatically inject jQuery Lint into the page as it is loaded (great for ad-hoc code validation)
  • FireFinder

Firefinder is an add-on to Firebug, to help find HTML elements
matching chosen CSS selector(s) or XPath expression. You can also
auto-select elements when hovering or via the context menu.

Example

  • You can't step through line by line or you'll end up in a whole bunch of jQuery functions.
  • You can't get into the inside of the each loop without either going through a lot of jQuery stuff or setting a breakpoint and letting it
    hit the breakpoint.

When I want to get inside a each loop and debug step-by-step, I create a breakpoint in the function which was passed to the each function and then I debug line-by-line until I reach jQuery code. Now I'm creating a new breakpoint at the position where the jQuery code ends and I want to continue to debug.

  • You can't see what any of the intermediate values like $(this) are or why it might be getting a bogus value for the height without
    stepping through miles of foreign jQuery code.

Look at http://msdn.microsoft.com/en-us/scriptjunkie/ee819093. There is explained how you can watch inside this for example (section 'Scenario 2'). This article gives many tips how to debug code which uses jQuery.

  • You can't break out of the each loop like you do in a traditional loop (with break or return) because it isn't an actual loop. The loop
    is inside the .each() function. What looks like a loop here is just
    the internals of a function call.

I don't understand this issue. You can break out of the each loop with returning false.
The function which was passed to the each function won't be called anymore when the function returned false one time.

  • What if I want to know why I'm getting a bogus height value in the loop. Is there any way to figure that out without stepping through a
    lot of jQuery code?

Maybe you'd have more information after looking into this as explained above. But sometimes it is necessary to look into jQuery code, but I don't do that very often. Of course there can be a bug in jQuery, too. :-D

Conclusion

Yes, debugging jQuery is a bit different. But I think after a small familiarization phase you will have modified your debugging style for jQuery. And moving from breakpoint to breakpoint is nothing compared to the time which was saved when using jQuery.

.



Related Topics



Leave a reply



Submit