Saturday, February 9, 2008

Modifying HTML/JSP Files with Ant

After compressing and concatenating your javascript files with YUI Compressor like I showed last week, you will probably want to have your build process modify your html/jsp files to point to them. To do this you can use an Ant task called replaceregexp.

Here is an example:

1. First modify your html so that it looks something like this:
<script type="text/javascript" src="scripts/MyFile1.js"></script>
<script type="text/javascript" src="scripts/MyFile2.js"></script>
<script type="text/javascript" src="scripts/MyFile3.js"></script>

Notice the @@myjs block. Everything between those comments (inclusive) will be replaced in the next step.

2. Add the following into your Ant build script:

<target name="set-js-includes" depends="init">
<fileset dir="../build/WebContent" includes="**/*.html, **/*.jsp">
<regexp pattern="&lt;!--@@myjs.start-->[-a-zA-Z0-9&lt;>\s'&quot;/=.!_]*&lt;!--@@myjs.end-->"/>
<substitution expression="&lt;script type=&quot;text/javascript&quot; src=&quot;scripts/MyFile.js&quot;>&lt;/script>"/>

You will need to make sure that the paths are pointing to the correct place.

Now you should have something that looks like this:

<script type="text/javascript" src="scripts/MyFile.js"></script>

After doing all of this there is an important question that must be asked: Why? Well, now you can have all of you javascript code neatly separated into different files during development, but built into one file that is faster to download for production. Just remember to test the output of this procedure as it will modify your code.

Have a good one.

No comments: