I'm making a Chrome extension that lets you choose a size of an item and check out quickly.
I have a value called "Large" in sizePref
array in my chrome.storage. And when it calls that value, it will choose an option in a dropdown based on that. However, possible labels are "Large", "L", "M/L" or "L/XL" ("Large" being the most often) with the value changing each time.
What is the most efficient way for me to ensure that it makes the correct selection (assuming the speed of doing so is the highest priority)?
This is my current code which just chooses "L" if "Large" doesn't exist. This code works without errors, but I want it to be improved.
chrome.storage.sync.get('sizePref', function(items) { // Get size preferences from storage
var sizePref = items.sizePref.top1; // Set size to a var
var sizeVal = $("#size option").filter(function() {
return $(this).html() == sizePref;
}).val();
var sizeVal2 = $("#size option").filter(function() {
return $(this).html() == "L";
}).val();
if (sizeVal !== undefined) {
$("#size").val(sizeVal);
} else {
$("#size").val(sizeVal2);
}
});
The targeted dropdown code is as follows:
<select id="size" name="size"><option value="25243">Small</option>
<option value="25244">Medium</option>
<option value="25245">Large</option>
<option value="25246">XLarge</option></select>
1 Answer 1
If speed is important, then you should avoid unnecessary dom lookups.
For example,
if sizeVal
is not undefined
, then you'll never need another dom lookup for sizeVal2
.
You can rearrange the code accordingly:
var sizeVal = $("#size option").filter(function() {
return $(this).html() == sizePref;
}).val();
if (sizeVal !== undefined) {
$("#size").val(sizeVal);
} else {
var sizeVal2 = $("#size option").filter(function() {
return $(this).html() == "L";
}).val();
$("#size").val(sizeVal2);
}
I would go even further an cache the $("#size option")
,
and also move the repeated logic into a function:
var options = $("#size option");
function findSize(target) {
options.filter(function() { return $(this).html() == target; });
}
var size = findSize(sizePref).val() || findSize("L").val();
var $("#size").val(size);
Explore related questions
See similar questions with these tags.