Where should I put javascript libraries in a Grails app?

情到浓时终转凉″ 提交于 2019-12-30 05:45:26

问题


I have a couple of Javascript libraries of my own that do some nice prettyfying of my HTML pages and I want to include them in my gsp pages, particularly the landing page of my app. I have tried putting them in views folder and web-app/js and $APP_HOME/scripts but when I load my index.gsp the scripts don't show up.

I have also tried a variety of alternatives in my code none of which work...

<script src="mylib.js" type="text/javascript"></script>
<script src="js/mylib.js" type="text/javascript"></script>
<script src="scripts/mylib.js" type="text/javascript"></script>

I'm sure there is a clever grails way of doing this on the fly, but I really just want a location where I can place some boilerplate JavaScript code that I can use in my app. With convention over configuration in mind, what is the expected practice?


回答1:


With your JS file at: web-app/js/myLib.js, putting <g:javascript library="myLib" /> in your layout should I think be what you need.




回答2:


You should probably NOT use <g:javascript library="myLib" /> as that is meant to be used as a way to make AJAX calls library (scriptaculous, dojo, yahoo, jquery) indifferent. See grails javascript. Instead use <g:javascript src="myLib.js" />.




回答3:


There are two ways by which you can include JS file and JS library like scriptaculous

// actually imports '/app/js/myscript.js'
<g:javascript src="myscript.js" />

// imports all the necessary js for the scriptaculous library
<g:javascript library="scriptaculous" />

<g:javascript>alert('hello')</g:javascript>

Refer : http://grails.org/doc/latest/ref/Tags/javascript.html




回答4:


I think I found the answer...

If I use this tag in my gsp (rather than a straightforward javascript reference)

<g:javascript library="mylib" />     

Then when I look at the generated page source it refers to

<script type="text/javascript" src="/myapp/js/mylib.js"></script>

This corresponds to the folder web-app/js, so I dropped my script library in there and it works fine. The breakthrough was for me to a) rename my index.html to index.gsp and b) use the g:javascript tag.




回答5:


Use <g:javascript src="myscript.js" /> and place your script in web-app/js/myscript.js

For full detail and examples for both your own external scripts, in-line code and libraries see http://grails.org/doc/latest/ref/Tags/javascript.html.



来源:https://stackoverflow.com/questions/2044957/where-should-i-put-javascript-libraries-in-a-grails-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!