WebJars is an easy way for server-side developers (such as your humble servant) to manage client-side resources such as Bootstrap, jQuery and their like, within the same package management tool they use for their server-side libraries.
In essence, what WebJars does is package a set version of the client-side resource (CSS or JavaScript) in the META-INF/resources of a JAR and upload it on Maven Central.
Then, any Java EE compatible web-container makes the resource available under a static URL.
For example, for a JAR packaging META-INF/resources/webjars/bootstrap.3.0.3/js/bootstrap.js
, it can be referenced by webjars/bootstrap/3.0.3/css/bootstrap.css
.
Most providers offer a minified version of their resource, and it is packaged along in the JAR, so using a minified resource is a no-brainer (if the minified resource is packages along, of course). However, when using multiple WebJars, this increases the number of browser requests. Outside the context of WebJars, minimizing the number of requests could easily be achieved by using wro4j, a tool that manages both minifying and merging resources through lists of pre- and post-processors. A typical wro4j use-case was already described in an earlier article.
The good thing is that WebJars and wro4j can be integrated with ease through wro4j.xml configuration file. As it stands, wro4j.xml configures resources merging. Those resources may come from a variety of sources; typically, they are internal resource and are referenced by their path relative from the webapp root:
/sample.css
However, the power of wro4j is to be able to reference other kind of resources, including those packaged inside JARs:
classpath:META-INF/resources/webjars/bootstrap/3.0.3/css/bootstrap.css
And with this configuration line only, we merge the resource inside the WebJar with other resources.
From this point on, the merged resource can be referenced as the single resource inside our webapp.
The following displays a wro4j configuration file that creates a compound.css
file from an internal sample.css
and the Bootstrap WebJar.
<?xml version="1.0" encoding="UTF-8"?>
<groups xmlns="http://www.isdc.ro/wro">
<group name="compound">
<css>classpath:META-INF/resources/webjars/bootstrap/3.0.3/css/bootstrap.css</css>
<css>/sample.css</css>
</group>
</groups>
An example project in Maven/IntelliJ format is provided as an attachment.
Though having a single minified resource for JavaScript (and one for CSS) improves performance with HTTP/1.1, it seems it might not be the case with HTTP/2.0. |