Grails: Different ways to import External Javascript Files

In Grails, there are many ways to embed javascript files in your project. I shall demonstrate those that I know, and you can decide which one is a lot better based on your needs. Before we begin, you'll need to know the following:
  • Grails 2.0.0 (This is the version I am using for this example)
  • Be sure that you have an external javascript file saved under web-app/js
Option 1: The Traditional Way
If your file is saved online, you can do it the old way as presented below. There is nothing wrong with it, it works, but it's not very grails like.
<script src=""></script>
Option 2: The Grails Way
You can also do something like the one below. It's definitely a "grailsy" way to do it.
<g:javascript src="" >
If your javascript file is found within your project folder then you can do it like the one showed below. It imports a file called myscript.js which is found in your web-app/js folder.
<g:javascript src="myscript.js"/ >
Option 2: The Grails Config Way
I can't think of a better Anyhow, in this method, we register our javascript files as modules in our Config.groovy.
grails.resources.modules = {
resource url:'/js/jQuery.js'
myScript {
resource url:'/js/myScript.js'
dependsOn 'core'
Notice the line "dependsOn 'core'", it tells us the various prerequisites that myScript.js needs to function. It's not really necessary, but it does come in handy. You can also embed css files as you desire. To use it on our gsp, we'll have to use this snippet of code:
<r:require module="myScript" />
I prefer option 3. It's beautiful, it's neat and clean and I don't have to embed too many lines when a script needs a lot of prerequisites.
If you know another way, please do share it with me! :)

Written by

I am a software developer with 2 years of experience. I like cats. I like going to hackathons for free food and temporary lodging. I want to be a polyglot. Currently, I can speak languages like English, Korean, Java (it counts right?), Groovy, Ruby and C#. I aim to learn German as well.

2 (mga) puna:

  1. Fantastic tip, thanks for sharing! I feel same, third way of importing external resources is quite clean and beautiful.



© 2013 icodeya. All rights resevered.Designed by Templateism

Back To Top