Grails Resources Plugin and AJAX loaded javascript

sikrip picture sikrip · Jan 5, 2012 · Viewed 7.7k times · Source

I added the resources plug-in in a grails 1.3.7 application and everything works fine except javascript that is loaded asynchronously.

So if I have a template that contains a

<r:script>
    // javascript here
</r:script>

and load it via ajax the js code does not execute, and I get this error:

It looks like you are missing some calls to the r:layoutResources tag

which makes sense because the page has already been rendered and there is no r:layoutResources to handle the newly added r:script js code.

The only workaround I've found is to add render r.layoutResources(disposition:"defer") after the actual render(template:...) in the controller actions that render content asynchronously.

Is there any other more clear solution?

Answer

Peter Ledbrook picture Peter Ledbrook · Jan 6, 2012

A better approach would be to have a dedicated layout for your AJAX responses:

<g:layoutBody/>
<r:layoutResources disposition="defer"/>

If you're using Grails 2.0, you can specify the layout in the render method (render template: "...", layout: "ajax"). Otherwise, use layout by convention.