You read part 1, right? If you didn’t, start there first and come back!
So now that you know how important it is to reduce Wicket page size, let’s talk about the AttributeModifier/AttributeAppender. They are convenience behaviors that can be added to any Component in order to dynamically add or modify markup attributes such as class, style, etc.
A simple example
We can show a simple use-case of an AttributeModifier. Suppose you are using a Label to display a percentage in some sort of financial application. You want to change the background color to green in the case of a positive percentage, and red for negative. You might think of doing it this way using an AttributeModifier:
public class ProfitLabel extends Label {
ProfitLabel(String id, IModel<Double> model) {
super(id, model);
add(new AttributeModifier("style", model.getObject() > 0 ? "background-color-green" : "background-color-red"));
}
}
The problem is that everywhere you use this Label, you are also creating an additional behavior which increases the size of the Wicket page. We can replace with a different implementation.
Using onComponentTag()
We can achieve the same effect by overriding onComponentTag() instead of creating a Behavior:
public class ProfitLabel extends Label {
ProfitLabel(String id, IModel<Double> model) {
super(id, model);
}
@Override
protected void onComponentTag(final ComponentTag tag) {
super.onComponentTag(tag);
Double percent = (Double) getDefaultModelObject();
tag.put("style", percent > 0 ? "background-color-green" : "background-color-red");
}
}
Testing the impact of AttributeModifiers/Appenders
We can again create a test page to observe the difference in page size. The page will have a ListView that renders 100 Label’s each with a random background color. You can find the full source code on Github.
Results
Using AttributeModifier: 78 KB
Using onComponentTag: 50 KB
That’s a pretty big difference! As we have seen, Wicket provides us many convenient behaviors and components, but we must think carefully before using them. Ultimately, using a couple Behaviors here or there won’t matter much, but when you are dealing with highly reused code, think about how much they are contributing to the page size.
Use the debug bar to frequently keep an eye on the page size as well. It’s much easier to catch things sooner, rather than later. I hope you enjoy these posts about Wicket page size and would love to hear other ideas about reducing it!