Even though inline JavaScript is not a very good idea, there are times when we need to invoke some function from within our page. Usually, this is done by putting it at the bottom of the page. However, if we are following the best practices for adding JavaScript libraries, they are usually at the bottom of the layout GSP file. In this case, our JavaScript snippet which is within the body of our actual GSP gets appended to the top.
<script type="text/javascript">// <![CDATA[ jQuery(document).ready(function(){ someFunction(); }); // Will give an error jQuery not defined and is fetched only after the call of this function. // ]]></script> <script type="text/javascript" src="/js/jQuery.js">// <![CDATA[ // From the layout.
In such cases, we can use the pageProperty of GSP layouts to define a section which will be rendered based on where we choose to put it in the layout GSP file.
For example, we'll enclose the script tag within the page under a content tag with the attribute tag set to script.
<content tag="script"> <script type="text/javascript"> jQuery(document).ready(function(){ someFunction(); }); // ]]></script>
The content tag can be accessed in our layout GSP using the tag.
. . . <script type="text/javascript" src="/js/jQuery.js">// <![CDATA[ //From the layout. <g:pageProperty name="page.script"/> . .
Now, our inline JavaScript will work as expected.
// ]]>