I think Sitecore devs may have experienced this and hence posting here.
I would like to add Javascript methods in a view. But jQuery is referred in the body tag at the end (moving to head is not an option). So, there is a $ undefined error on page load.
@{
Layout = null;
}
<div>
....
</div>
<script>
$(document).ready(function(){
$("#btn").click(function(){
doSomething();
});
doSomething();
});
function doSomething(){
alert();
}
</script>
Things I have tried:
- Enclosing the script tag inside
@section Script {}
. There is no error in console but the alert is not triggered. - Added
@RenderSection("Scripts", required: false)
in the layout file. It throws an error that - "layout.cshtml cannot be requested directly because it calls the "RenderSection" method". - I never had the need to add Layout path in a view and always set it to null. As there was an error in step2, I specified the layout path in the view. Now there is an error about recursive rendering reference.
How can I add JS methods in the view, with jQuery still in the body tag.