Grails - Adding JavaScript to bottom of page

In Grails using the templating (Sitemesh) if you were to include per-page JavaScript resources then it shows up much earlier in the layout content as part of the <g:layoutBody>

Here is an example illustrating the problem:

SamplePage.gsp [sourcecode language=“html”]

MyThinkPond.com Custom Page ... Some this page content

[/sourcecode]

and the layout page (layoutPage.gsp) [sourcecode language=“html”]

<g:layoutTitle default="MyThinkPond.com"/> ...
Some template (header) content

[/sourcecode]

results in the following page in browser [sourcecode language=“html”]

...
Some template (header) content Some this page content
[/sourcecode]

You can see that the JavaScript is included as part of the body and not at the bottom.

Here’s how you resolve this issue:

In your custom page, define a content block like this:

SamplePage.gsp [sourcecode language=“html”]

MyThinkPond.com Custom Page ... Some this page content [/sourcecode]

In your template layout page add the content block to the bottom as needed like this: layoutPage.gsp [sourcecode language=“html”]

<g:layoutTitle default="MyThinkPond.com"/> ...
Some template (header) content

[/sourcecode]

This will extract the JavaScript portion from samplePage and insert at the bottom of the layoutPage.

Here is the result of this magic in a page in the browser: [sourcecode language=“html”]

...
Some template (header) content Some this page content
[/sourcecode]

You can see that the page specific JavaScript content got added towards the bottom as you intended it to be.

If this article has helped you, please add this article to your favorite social links so that others may also find this article.

Cheers & Happy Coding!