* @param name Can't be blank.
* @param attributes May be {@code null}.
* @return Never {@code null}.
*/
public HtmlElement findOrCreateHeadElement(String name, Object... attributes) {
HtmlElement element = findHeadElement(name, attributes);
if (element == null) {
element = new HtmlElement();
element.setName(name);
element.addAttributes(attributes);
List<HtmlNode> nodes = getHeadNodes();
if (ObjectUtils.isBlank(nodes)) {
nodes.add(element);
} else {
// JS goes last.
if ("script".equals(name)) {
nodes.add(element);
// CSS goes first.
} else if ("link".equals(name) &&
"text/css".equals(element.getAttributes().get("type"))) {
int insertIndex = 0;
for (ListIterator<HtmlNode> i = nodes.listIterator(); i.hasNext();) {
HtmlNode node = i.next();
if (!(node instanceof HtmlElement)) {
continue;
}
HtmlElement iElement = (HtmlElement) node;
if ("link".equals(iElement.getName()) &&
"text/css".equals(iElement.getAttributes().get("type"))) {
continue;
} else {
insertIndex = i.previousIndex();
break;
}
}
nodes.add(insertIndex, element);
// Everything else in between.
} else {
int insertIndex = 0;
for (ListIterator<HtmlNode> i = nodes.listIterator(); i.hasNext();) {
HtmlNode node = i.next();
if (!(node instanceof HtmlElement)) {
continue;
}
HtmlElement iElement = (HtmlElement) node;
if ("script".equals(iElement.getName())) {
insertIndex = i.previousIndex();
break;
} else {
insertIndex = i.nextIndex();