I have a application built on groovy and Grails (grails version 2.0.4). I;m using the grails jQuery -plugin
in a gsp page if i try something like this
<script type="text/javascript">
$(document).ready(function() {
alert($);
});
</script>
gives me in error in console
Uncaught ReferenceError: $ is not defined list:24
(anonymous function)
but if i try something like this
<r:script>
$(document).ready(function() {
alert($);
});
</r:script>
it alerts as expected.
grails jQuery plugin installs jquery version 1.7.1
what is causes this behavior/error?
when i see the page source i see that jQuery is loaded after the script tag
how to fix it?
My main.gsp page
<!doctype html>
<!--[if lt IE 7 ]> <html lang="en" class="no-js ie6"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="no-js ie7"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="no-js ie8"> <![endif]-->
<!--[if IE 9 ]> <html lang="en" class="no-js ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="en" class="no-js"><!--<![endif]-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<r:require modules="jquery"/>
<title><g:layoutTitle default="Grails"/></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="${resource(dir: 'images', file: 'favicon.ico')}" type="image/x-icon">
<link rel="apple-touch-icon" href="${resource(dir: 'images', file: 'apple-touch-icon.png')}">
<link rel="apple-touch-icon" sizes="114x114" href="${resource(dir: 'images', file: 'apple-touch-icon-retina.png')}">
<link rel="stylesheet" href="${resource(dir: 'css', file: 'main.css')}" type="text/css">
<link rel="stylesheet" href="${resource(dir: 'css', file: 'mobile.css')}" type="text/css">
<g:layoutHead/>
<g:javascript library="jquery"/>
<r:require module="application"/>
<r:layoutResources />
</head>
<body>
<div id="spinner" class="spinner" style="display:none;"><g:message code="spinner.alt" default="Loading…"/></div>
<div class="page_header">
<g:render template="/templates/header" />
</div>
<div class="container">
<div class="left_column">
<g:render template="/templates/commonMenu" />
</div>
<div class="center">
<g:layoutBody />
</div>
</div>
<div class="footer">
<g:render template="/templates/footer" />
</div>
</body>
</html>
Check documentation of the Grails Resourses plugin first to understand how it works and how to use it.
When you use script tag it will be rendered where it was defined. But if you use r:script then it will be rendered after all modules (including jQuery) at the end of the page (usually).