Minify .js files during Maven builds

Minifying files for use on the web is essential to improving performance, to reduce network overhead as well as a slight bump in execution speed.

Long ago I used the YUICompressor plugin for both JS as well as CSS files, unfortunately that project appears to have been abandoned many years ago and no longer functions well for JS files that make use of modern features.

For JS files, I’ve found that most capabilities can be replicated with the following in the pom.xml:

<plugin>
<groupId>com.github.blutorange</groupId>
<artifactId>closure-compiler-maven-plugin</artifactId>
<version>2.21.0</version>
<executions>
<execution>
<id>default-minify-js</id>
<phase>generate-resources</phase>
<configuration>
<!-- not supported (always uses .min) <suffix>-min</suffix> -->
<encoding>UTF-8</encoding>
<baseSourceDir>${basedir}/${webapp-folder}</baseSourceDir>
<baseTargetDir>${webapp.path}/</baseTargetDir>
<sourceDir>js</sourceDir>
<targetDir>js</targetDir>
<skipMerge>true</skipMerge>
<includes>
<include>**/*.js</include>
</includes>
<excludes>
<exclude>**/webjars-requirejs.js</exclude>
<exclude>**/bootstrap*.*</exclude>
<exclude>**/jasmine*.*</exclude>
<exclude>**/*-min.js</exclude>
<exclude>**/*.min.js</exclude>
</excludes>
</configuration>
<goals>
<goal>minify</goal>
</goals>
</execution>
</executions>
</plugin>

NOTE: the only feature I have not yet been able to match is the suffix, as it appears to always use *.min.js (where I used to prefer *-min.js).

An additional advantage of using the plugin is that many common syntax errors will be identified at build time, before they cause user problems… but they will also break your build!

REFERENCES:

Using comments to ‘hide’ SCRIPT tag content – please stop this obsolete practice

Many years ago, when HTML3 and 4 were still widely used in the mid to late 1990s, it was a common practice to place HTML style comments, or in some cases CDATA comments inside the SCRIPT tag in an attempt to hide that content from browsers that could not process it. In those browsers the content (javascript source code) would sometimes be displayed on the page, making it quite a mess.

This practice is now obsolete, and often problematic as there are very few of those browsers in use today – primarily only for testing of legacy functionality.

Example of old approach

<script type="text/javascript">
<--
// some script
-->
</script>

NOTE: for XHTML or XML documents, the use of a CDATA style comment is still required.
<script type=”text/javascript”>
//<![CDATA[
…code…
//]]>
</script>

REFERENCES:

Redirect within a javascript file

There often comes a time when you are working on a large project and find a need to refactor javascript resources. Unfortunately, if those assets are accessed by 3rd parties or other code you cannot easily update, you might find yourself stuck.

If you have access to the Tier1 (HTTP server such as ApacheHTTPd) you can often do this within the httpd.conf, or an .htaccess file update. If not, you can always do a simple function within the old javascript file itself, such as the one below.

Put this in the old javascript file location, it is in a closure to prevent the variables from “leaking” into the global namespace.


/* MOVED */
(function(){
"use strict";
var u='/js/newfile.js';
var t=document.createElement('script');t.type='text/javascript';t.src=u;
var s=document.getElementsByTagName('script')[0];s.parentNode.insertBefore(t,s);
})();

HTML4 script defer

This HTML4 attribute was intended to defer/delay execution of specific javascript code until after the page is rendered. In theory, this makes the website “appear” faster as the functions relevant to the User-Interface can be executed before other “background” processes that would otherwise block the screen from displaying.


<script defer="defer" src="example.js"></script>

NOTE: Do not use defer for external scripts that might depend on each other if you need to support MSIE9 and earlier.

REFERENCES:

HTML5 script async

The HTML5 “async” attribute simplifies page-load performance improvements and dynamic script loading, it can be useful in modern web browsers.

Simply put, this tag allows for the browser to asynchronously load and execute external javascript files in a parallel vs. serial manner. Unfortunately while most modern browser support it, MSIE versions prior to MSIE10+ are problematic.


<script src="example.js" async="async"></script>

This is particularly useful when using third-party javascript libraries and utilities that have no dependeny relationships with your existing website javascript.

REFERENCES:

Javascript “this” keyword

The “this” keyword is an indispensable, yet often mis-understood, concept in JavaScript object-oriented programming. When used in a JavaScript constructor function, “this” refers to the specific instance of the Object. Through the “this” keyword, properties and methods can be assigned object, also known as a class.

For example:

function Square(intSideLength)
{
this.sideLength = intSideLength;
}

In the preceding example the “this” keyword is used to assign the variable “sideLength” as a property of the Square class.
The “this” keyword is also frequently passed as a parameter on JavaScript events, such as when a checkbox is clicked. In such an instance, “this” refers to the current object, the checkbox.

REFERENCES:

Maven build script for replacement of text in web.xml (and others)

Automated replacement of BUILD_LABEL token in web.xml <description> with Maven. For JAR’s the replacement is commented out, but can be any file.

NOTE: This proves to be rather difficult to do because of the way that Maven copies resources as it’s building the WAR. The most reliable manner I’ve found (so far) is below, it works by making a .tmp copy of the web.xml in a different path and then later uses it in the WAR.


<plugins>
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>replacer</artifactId>
<version>1.5.3</version>
<configuration>
<quiet>false</quiet>
</configuration>
<executions>
<execution>
<id>replaceBuildLabel</id>
<phase>prepare-package</phase>
<goals>
<goal>replace</goal>
</goals>
<configuration>
<file>${basedir}/src/main/webapp/WEB-INF/web.xml</file>
<outputFile>${project.build.directory}/web.xml.tmp</outputFile>
<replacements>
<replacement>
<token>BUILD_LABEL</token>
<value>Maven-${maven.build.timestamp}</value>
</replacement>
</replacements>
<regex>false</regex>
<quiet>false</quiet>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.5</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<webXml>${project.build.directory}/web.xml.tmp</webXml>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
<manifestEntries>
<url>${project.url}</url>
<Build-Label>${maven.build.timestamp}</Build-Label>
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>

Most importantly, you will want to have this token in the web.xml file for replacement, the description line is best used for this as such:

<description>ExampleWAR [BUILD_LABEL]</description>

during the build, that value would be replaced to something like:

<description>ExampleWAR [Maven-20141015-1700]</description>

REFERENCES:

Ant build script for replacement of text in web.xml (and others)

Automated replacement of BUILD_LABEL in web.xml <description> with Ant. For JAR’s the replacement is commented out, but can be any file


<replace file="${webapp.dir}/WEB-INF/web.xml" token="BUILD_LABEL" value="Ant-${DSTAMP}-${TSTAMP}" />
<war destfile="${jar.dir}/${ant.project.name}.war" webxml="${webapp.dir}/WEB-INF/web.xml" compress="true">

Most importantly, you will want to have this token in the web.xml file for replacement, the description line is best used for this as such:

<description>ExampleWAR [BUILD_LABEL]</description>

during the build, that value would be replaced to something like:

<description>ExampleWAR [Ant-20141015-1700]</description>

REFERENCES:

Content-Security-Policy HTTP Header

There’s yet another new means to ‘help’ client User-Agents with preventing XSS on your websites.

In it’s simplest form you can simply use the following HTTP Header(s), the second one is for earlier versions of Webkit (Chrome/Safari):

Content-Security-Policy: default-src 'self'
Webkit-CSP: default-src 'self'

You can also add to the above to permit assets to load from other sources.
For example, if you were to permit javascript files from example.com you could include:

Content-Security-Policy: default-src 'self'; script-src http://example.com

Additionally, while failures are noted in the client’s browser console (that most users are not aware of), you can have them sent back to your server by adding a ‘report-uri’ attribute with an appropriate handler:

Content-Security-Policy: default-src 'self'; report-uri http://example.com/csp-report.php

REFERENCES:

Google Web Fonts

The use of non-traditional web fonts was once a very challenging task due to various browser specific implementations. Thankfully Google WebFonts have made this easy enough for most developers to add in a cross-browser manner in a matter of minutes.

WARNING, there are a few considerations to make here…

  1. Some browsers displays a blank space in place of the text that uses the font.
  2. … and then re-render text in the web font once it has loaded

Method 1: (most compatible, but cross-browser loading behavior varies)

<link href='http://fonts.googleapis.com/css?family=Ubuntu:400,700' rel='stylesheet' type='text/css' />
<style type="text/css">
h1,p { font-family: 'Ubuntu', sans-serif; }
</style>

Method 2: (requires javascript, but is consistent cross-browser)

<script type="text/javascript">
WebFontConfig = {
google: { families: [ 'Ubuntu Mono','Ubuntu' ] }
};
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
</script>
<style type="text/css">
h1 { font-family: 'Ubuntu Mono','Courier New',monospace; }
p { font-family: 'Ubuntu','sans-serif'; }
</style>