Grails - Adding JavaScript to bottom of page | MyThinkPond

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

Here is an example illustrating the problem:

SamplePage.gsp [sourcecode language=“html”] <!DOCTYPE html> MyThinkPond.com Custom Page … Some this page content

[/sourcecode]

and the layout page (layoutPage.gsp) [sourcecode language=“html”] <!DOCTYPE html> <g:layoutTitle default="MyThinkPond.com"/>

Some template (header) content

[/sourcecode]

results in the following page in browser [sourcecode language=“html”] <!DOCTYPE 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”] <!DOCTYPE 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”] <!DOCTYPE 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”] <!DOCTYPE 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!

Venkatt Guhesan avatar
About Venkatt Guhesan
Enterprise Software Architect currently working at DataDirect Networks developing a highly scalable monitoring solution called DDN Insight. My passions include all things Open Source including Linux (CentOS, Red Hat, Gentoo, Open Stack, Docker & Ubuntu), embedded ARM processors and microcontrollers (Arduino, UDOO, Cubieboard, BeagleBoard, OnionIO, TI's Zigbee). Coming from an Electrical and Computer Engineering background, working in developing and designing enterprise - distributed, highly scalable software requires a unique set of software skills with a good understanding of the hardware. This makes his work challenging and interesting. In his free time, he spends his time with his family and two children. He also enjoys researching on topics including - world ancient history and yoga. Visit the 'About' section for more details.
comments powered by Disqus