I am new to jQuery, and after spending weeks to convert my pages using jQuery, I am now reading about jQuery optimization. In that effort, I'm rewriting one of my functions. Please comment whether it is right (both are working).
Previous
$("#mydiv").empty();
var i = 2;
$("#axisa option").each(function() {
$("#mydiv").append("<div id='tempdiv"+i+"'></div>");
updateCharts($("#wd").slider("value"), $("#ht").slider("value"),$(this).val());
i++
});
$("#axisb option").each(function() {
$("#mydiv").append("<div id='tempdiv"+i+"'></div>");
updateCharts($("#wd").slider("value"), $("#ht").slider("value"),$(this).val());
i++
});
$("#hiddendiv").show("slow");
Optimized
var mydiv = $("#mydiv");
var mywid = $("#wd").slider("value");
var myhet = $("#ht").slider("value");
var total = $("#axisa option").length + $("#axisb option").length+2;
mydiv.empty();
var design = "";
for(var i=2;i<total;i++){
design += "<div id='tempdiv"+i+"'></div>";
}
mydiv.append(design);
i = 2;
$("#axisa option").each(function() {
updateCharts(mywid, myhet, $(this).val());
i++
});
$("#axisb option").each(function() {
updateCharts(mywid, myhet, $(this).val());
i++
});
$("#hiddenDiv").show("slow");
1 Answer 1
Here are some general optimizations that I usually do.
When you have multiple var declarations you can separate with "," making it a bit easier to read and less of a hassle to write:
var mydiv = $("#mydiv").empty(),
mywid = $("#wd").slider("value"),
myhet = $("#ht").slider("value"),
etc = etc.....
Also when I name my variables, ids, classes, etc. it's good to put names that reference what's inside the element, or the role it plays. It will help you remeber what does what when you get into big projects with lots of these declarations.
As a rule of thumb, if you have to call on an element more than once, you should cache its value. This way jQuery doesn't have to jump into the DOM and look for that element each time you call it. You should also try to limit the scope of elements jQuery has to look through to find the one you want. You can use the type of element previous to the id/class. For example:
$("#mydiv").doSomething();
$("#mydiv").doSomethingElse();
Instead do:
var mydiv = $("div #mydiv");
$(mydiv).doSomething();
$(mydiv).doSomethingElse();
Like you said, you are just starting out with jQuery, and with that I highly recommend this screencast by Jeffrey Way called 30 Days to Learn jQuery. He does a really good job of explain some basic principals as well as some more complex concepts.
mydiv
as a variable, but then you still use$('#mydiv')
. Could you throw this up into a jsFiddle with some target HTML? I'm not quite clear on what you are trying to do. \$\endgroup\$$("#mydiv").append(design)
when you could have usedmydiv.append(design)
. Larger picture though -- I don't know what your code is trying to accomplish. \$\endgroup\$