Put JavaScript at the Bottom with Grails Asset-Pipeline


With the Grails Resource plugin you can use a gsp layout like this:

<!DOCTYPE html>
<html>
<head>
    <g:layoutHead/>
    <r:layoutResources /> 
</head>
<body>
   <g:layoutBody/>


   <g:javascript library="jquery" plugin="jquery" /> 

   <r:layoutResources />

</body>

Using the r:layoutResources tag you can specify that resources should be included at the bottom of the page after the JQuery, which is at the bottom of the layout gsp.

Is there a way to do the same with the asset-pipeline plugin? How can I put resources at the bottom of the document event after the JQuery include?

I just add lines at the bottom of my .gsp or layout files:

<asset:stylesheet src="xxx.css"/>
<asset:javascript src="xxx.js"/>

xxx.js and xxx.css can include a manifest to load more stuff.

You would load JQuery via the manifest(s):

xxx.js:

//= require jquery
//= require select2.min.js
//= require_self

In your layout file, put this:

<html>
<body>
....
<!-- Your layout scripts -->
<asset:javascript src="app.js"/>

<!-- Custom placeholder for page scripts -->
<g:ifPageProperty name="page.footScripts">
    <g:pageProperty name="page.footScripts" />
</g:ifPageProperty>

</body>
</html>

And in your page (i.e. index.gsp ), put this

<html>
<body>
...
...
</body>
</html>

<content tag="footScripts">
    <asset:javascript src="jqueryui/jquery-ui.min"/>
</content>

This way, you can extend your layouts with content defined in your individual pages.

Grails 3 documentation ( though the same in Grails 2 )

See chapter 8.2.6 Sitemesh Content Blocks


If you want to add multiple scripts on your child scripts, you can do it like

Bottom of your parent.gsp

<g:each in="${pageScript}">
    <asset:javascript src="${it.value}.js"/>
</g:each>

Your child.gsp

<g:set var="pageScript" value="['script1, script2']"/>

You can solve this with the <g:pageProperty/> tag, no matter what plugins you use (anyway, I tested the solution with asset-pipeline like you).

A tutorial with the solution is here: http://mythinkpond.com/2014/02/02/grails-adding-javascript-bottom-page/