7.2.5 Static Resources - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari
Version: 2.3.8
Table of Contents
7.2.5 Static Resources
Grails 2.0 integrates with the Resources plugin to provide sophisticated static resource management. This plugin is installed by default in new Grails applications.The basic way to include a link to a static resource in your application is to use the resource tag. This simple approach creates a URI pointing to the file.However modern applications with dependencies on multiple JavaScript and CSS libraries and frameworks (as well as dependencies on multiple Grails plugins) require something more powerful.The issues that the Resources framework tackles are:- Web application performance tuning is difficult
- Correct ordering of resources, and deferred inclusion of JavaScript
- Resources that depend on others that must be loaded first
- The need for a standard way to expose static resources in plugins and applications
- The need for an extensible processing chain to optimize resources
- Preventing multiple inclusion of the same resource
7.2.5.1 Including resources using the resource tags
Pulling in resources with r:require
To use resources, your GSP page must indicate which resource modules it requires. For example with the jQuery plugin, which exposes a "jquery" resource module, to use jQuery in any page on your site you simply add:<html> <head> <r:require module="jquery"/> <r:layoutResources/> </head> <body> … <r:layoutResources/> </body> </html>
r:require
multiple times in a GSP page, and you use the "modules" attribute to provide a list of modules:<html> <head> <r:require modules="jquery, main, blueprint, charting"/> <r:layoutResources/> </head> <body> … <r:layoutResources/> </body> </html>
Rendering the links to resources with r:layoutResources
When you have declared the resource modules that your GSP page requires, the framework needs to render the links to those resources at the correct time.To achieve this correctly, you must include the r:layoutResources tag twice in your page, or more commonly, in your GSP layout:<html> <head> <g:layoutTitle/> <r:layoutResources/> </head> <body> <g:layoutBody/> <r:layoutResources/> </body> </html>
Adding page-specific JavaScript code with r:script
Grails has the javascript tag which is adapted to defer to Resources plugin if installed, but it is recommended that you callr:script
directly when you need to include fragments of JavaScript code.This lets you write some "inline" JavaScript which is actually not rendered inline, but either in the <head> or at the end of the body, based on the disposition.Given a Sitemesh layout like this:<html> <head> <g:layoutTitle/> <r:layoutResources/> </head> <body> <g:layoutBody/> <r:layoutResources/> </body> </html>
<html> <head> <title>Testing r:script magic!</title> </head> <body> <r:script disposition="head"> window.alert('This is at the end of <head>'); </r:script> <r:script disposition="defer"> window.alert('This is at the end of the body, and the page has loaded.'); </r:script> </body> </html>
Linking to images with r:img
This tag is used to render<img>
markup, using the Resources framework to process the resource on the fly (if configured to do so - e.g. make it eternally cacheable).This includes any extra attributes on the <img>
tag if the resource has been previously declared in a module.With this mechanism you can specify the width, height and any other attributes in the resource declaration in the module, and they will be pulled in as necessary.Example:<html> <head> <title>Testing r:img</title> </head> <body> <r:img uri="/images/logo.png"/> </body> </html>
g:img
tag as a shortcut for rendering <img>
tags that refer to a static resource. The Grails img tag is Resources-aware and will delegate to r:img
if found. However it is recommended that you use r:img
directly if using the Resources plugin.Alongside the regular Grails resource tag attributes, this also supports the "uri" attribute for increased brevity.See r:resource documentation for full details.
7.2.5.2 Other resource tags
r:resource
This is equivalent to the Grails resource tag, returning a link to the processed static resource. Grails' owng:resource
tag delegates to this implementation if found, but if your code requires the Resources plugin, you should use r:resource
directly.Alongside the regular Grails resource tag attributes, this also supports the "uri" attribute for increased brevity.See r:resource documentation for full details.r:external
This is a resource-aware version of Grails external tag which renders the HTML markup necessary to include an external file resource such as CSS, JS or a favicon.See r:resource documentation for full details.7.2.5.3 Declaring resources
A DSL is provided for declaring resources and modules. This can go either in yourConfig.groovy
in the case of application-specific resources, or more commonly in a resources artefact in grails-app/conf
.Note that you do not need to declare all your static resources, especially images. However you must to establish dependencies or other resources-specific attributes. Any resource that is not declared is called "ad-hoc" and will still be processed using defaults for that resource type.Consider this example resource configuration file, grails-app/conf/MyAppResources.groovy
:modules = { core { dependsOn 'jquery, utils' resource url: '/js/core.js', disposition: 'head' resource url: '/js/ui.js' resource url: '/css/main.css', resource url: '/css/branding.css' resource url: '/css/print.css', attrs: [media: 'print'] } utils { dependsOn 'jquery' resource url: '/js/utils.js' } forms { dependsOn 'core,utils' resource url: '/css/forms.css' resource url: '/js/forms.js' } }
bundle:'someOtherName'
on each resource, or call defaultBundle
on the module (see resources plugin documentation).It declares dependencies between them using dependsOn
, which controls the load order of the resources.When you include an <r:require module="forms"/>
in your GSP, it will pull in all the resources from 'core' and 'utils' as well as 'jquery', all in the correct order.You'll also notice the disposition:'head'
on the core.js
file. This tells Resources that while it can defer all the other JS files to the end of the body, this one must go into the <head>
.The CSS file for print styling adds custom attributes using the attrs
map option, and these are passed through to the r:external
tag when the engine renders the link to the resource, so you can customize the HTML attributes of the generated link.There is no limit to the number of modules or xxxResources.groovy artefacts you can provide, and plugins can supply them to expose modules to applications, which is exactly how the jQuery plugin works.To define modules like this in your application's Config.groovy, you simply assign the DSL closure to the grails.resources.modules
Config variable.For full details of the resource DSL please see the resources plugin documentation.
7.2.5.4 Overriding plugin resources
Because a resource module can define the bundle groupings and other attributes of resources, you may find that the settings provided are not correct for your application.For example, you may wish to bundle jQuery and some other libraries all together in one file. There is a load-time and caching trade-off here, but often it is the case that you'd like to override some of these settings.To do this, the DSL supports an "overrides" clause, within which you can change thedefaultBundle
setting for a module, or attributes of individual resources that have been declared with a unique id:modules = { core { dependsOn 'jquery, utils' defaultBundle 'monolith' resource url: '/js/core.js', disposition: 'head' resource url: '/js/ui.js' resource url: '/css/main.css', resource url: '/css/branding.css' resource url: '/css/print.css', attrs: [media: 'print'] } utils { dependsOn 'jquery' defaultBundle 'monolith' resource url: '/js/utils.js' } forms { dependsOn 'core,utils' defaultBundle 'monolith' resource url: '/css/forms.css' resource url: '/js/forms.js' } overrides { jquery { defaultBundle 'monolith' } } }
7.2.5.5 Optimizing your resources
The Resources framework uses "mappers" to mutate the resources into the final format served to the user.The resource mappers are applied to each static resource once, in a specific order. You can create your own resource mappers, and several plugins provide some already for zipping, caching and minifying.Out of the box, the Resources plugin provides bundling of resources into fewer files, which is achieved with a few mappers that also perform CSS re-writing to handle when your CSS files are moved into a bundle.Bundling multiple resources into fewer files
The 'bundle' mapper operates by default on any resource with a "bundle" defined - or inherited from adefaultBundle
clause on the module. Modules have an implicit default bundle name the same as the name of the module.Files of the same kind will be aggregated into this bundle file. Bundles operate across module boundaries:modules = { core { dependsOn 'jquery, utils' defaultBundle 'common' resource url: '/js/core.js', disposition: 'head' resource url: '/js/ui.js', bundle: 'ui' resource url: '/css/main.css', bundle: 'theme' resource url: '/css/branding.css' resource url: '/css/print.css', attrs: [media: 'print'] } utils { dependsOn 'jquery' resource url: '/js/utils.js', bundle: 'common' } forms { dependsOn 'core,utils' resource url: '/css/forms.css', bundle: 'ui' resource url: '/js/forms.js', bundle: 'ui' } }
Making resources cache "eternally" in the client browser
Caching resources "eternally" in the client is only viable if the resource has a unique name that changes whenever the contents change, and requires caching headers to be set on the response.The cached-resources plugin provides a mapper that achieves this by hashing your files and renaming them based on this hash. It also sets the caching headers on every response for those resources. To use, simply install the cached-resources plugin.Note that the caching headers can only be set if your resources are being served by your application. If you have another server serving the static content from your app (e.g. Apache HTTPD), configure it to send caching headers. Alternatively you can configure it to request and proxy the resources from your container.Zipping resources
Returning gzipped resources is another way to reduce page load times and reduce bandwidth.The zipped-resources plugin provides a mapper that automatically compresses your content, excluding by default already compressed formats such as gif, jpeg and png.Simply install the zipped-resources plugin and it works.Minifying
There are a number of CSS and JavaScript minifiers available to obfuscate and reduce the size of your code. At the time of writing none are publicly released but releases are imminent.7.2.5.6 Debugging
When your resources are being moved around, renamed and otherwise mutated, it can be hard to debug client-side issues. Modern browsers, especially Safari, Chrome and Firefox have excellent tools that let you view all the resources requested by a page, including the headers and other information about them.There are several debugging features built in to the Resources framework.X-Grails-Resources-Original-Src Header
Every resource served in development mode will have the X-Grails-Resources-Original-Src: header added, indicating the original source file(s) that make up the response.Adding the debug flag
If you add a query parameter _debugResources=y to your URL and request the page, Resources will bypass any processing so that you can see your original source files.This also adds a unique timestamp to all your resource URLs, to defeat any caching that browsers may use. This means that you should always see your very latest code when you reload the page.Turning on debug all the time
You can turn on the aforementioned debug mechanism without requiring a query parameter, but turning it on in Config.groovy:grails.resources.debug = true
7.2.5.7 Preventing processing of resources
Sometimes you do not want a resource to be processed in a particular way, or even at all. Occasionally you may also want to disable all resource mapping.Preventing the application of a specific mapper to an individual resource
All resource declarations support a convention of noXXXX:true where XXXX is a mapper name.So for example to prevent the "hashandcache" mapper from being applied to a resource (which renames and moves it, potentially breaking relative links written in JavaScript code), you would do this:modules = { forms { resource url: '/css/forms.css', nohashandcache: true resource url: '/js/forms.js', nohashandcache: true } }
Excluding/including paths and file types from specific mappers
Mappers have includes/excludes Ant patterns to control whether they apply to a given resource. Mappers set sensible defaults for these based on their activity, for example the zipped-resources plugin's "zip" mapper is set to exclude images by default.You can configure this in yourConfig.groovy
using the mapper name e.g:// We wouldn't link to .exe files using Resources but for the sake of example: grails.resources.zip.excludes = ['**/*.zip', '**/*.exe']// Perhaps for some reason we want to prevent bundling on "less" CSS files: grails.resources.bundle.excludes = ['**/*.less']
Controlling what is treated as an "ad-hoc" (legacy) resource
Ad-hoc resources are those undeclared, but linked to directly in your application without using the Grails or Resources linking tags (resource, img or external).These may occur with some legacy plugins or code with hardcoded paths in.There is a Config.groovy setting grails.resources.adhoc.patterns which defines a list of Servlet API compliant filter URI mappings, which the Resources filter will use to detect such "ad-hoc resource" requests.By default this is set to:grails.resources.adhoc.patterns = ['images/*', '*.js', '*.css']