【问题标题】:JavaScript file doesn't loadJavaScript 文件不加载
【发布时间】:2017-05-03 02:19:16
【问题描述】:
我正在使用 Spring MVC、Thymeleaf 并希望在我的 html 文档中导入一个 javascript 文件。尽管所有链接都设置正确并且文件出现在我浏览器的调试视图中,但它们不会加载。
HTML 中有以下 JS 应该调用 datepicker,但它没有显示出来:
<script th:inline="javascript">
/*<![CDATA[*/
$( function() {
$( "#datepicker" ).Datepicker(
);
} );
/*]]>*/
</script>
文件以这种方式包含:
<script type="text/javascript" th:src="@{/resources/js/file.js}"></script>
CSS 文件只要改变类型就可以正常工作。
任何想法如何解决这个问题?
Shows error on Chrome debugging
现在我从导入中删除了所有不需要的 js 文件,它显示以下错误:
more precise error
这说明使用的是jquery-1.12.4。
【问题讨论】:
标签:
javascript
jquery
html
spring-mvc
thymeleaf
【解决方案1】:
当您使用 Spring 和 Thymeleaf 时,建议使用以下项目结构:
src
|-main
|-resources
|-static
| |-css
| |-bootstrap.min.css
| |-application.css
| |-images
| |-js
| |-jquery-3.1.1.js
|-templates
然后在您的模板中包含不同的资源将如下所示:
<head>
<link href="../static/css/bootstrap.min.css" rel="stylesheet" media="screen"
th:href="@{/css/bootstrap.css}"/>
<link href="../static/css/application.css" rel="stylesheet" media="screen"
th:href="@{/css/application.css}"/>
<script src="../static/js/jquery-3.1.1.js"
th:src="@{/js/jquery-3.1.1.js}"></script>
</head>
【解决方案2】:
答案:
1) <th:block></th:block> 没有区别
2) 对html标签的补充
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
没有区别
3) 将带有内容的 script-tags 放置在 body 底部与放置在 head 中时相同
4) 我在这个项目中使用了 Bootstrap,并在 Bootstrap 的一个 div 中使用了 datepicker。将它放在身体的其他地方而不是放在 div 内之后,它就起作用了。
结论:
如果您使用 Spring MVC 和 Thymeleaf 并希望包含所需的 JavaScript 文件:
1) <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
2)<link th:href="@{/resources/.../file.css}" rel="stylesheet" type="text/css"/>
3)<script type="text/javascript" th:src="@{/resources/.../file.js}"></script>
4) 确保您的 JS 或 CSS 文件没有被以下文件“覆盖”
感谢您的时间和帮助@Parth!