JavaScript file doesn't load

2019-07-25 09:25发布

问题:

I'm using Spring MVC, Thymeleaf and want to import a javascript file in my html document. Although all links are set correctly and the files appear in the debugging view in my browser, they don't load. There is following JS in the HTML that should call a datepicker, but it doesn't show up:

<script th:inline="javascript">
/*<![CDATA[*/
  $( function() {
    $( "#datepicker" ).Datepicker(
      );
  } );
/*]]>*/
</script>

the files are included this way:

  <script type="text/javascript" th:src="@{/resources/js/file.js}"></script>

CSS files work just fine just with the type changed.

Any ideas how to fix this?

Shows error on Chrome debugging

Now I deleted all not necessary js files from the import and it shows following error:

more precise error

This shows that the jquery-1.12.4 is used.

回答1:

When you are using Spring and Thymeleaf the following project structure is recommended:

src
   |-main
       |-resources
           |-static
           |   |-css
           |       |-bootstrap.min.css
           |       |-application.css
           |   |-images
           |   |-js
           |       |-jquery-3.1.1.js
           |-templates

Then including different resources in your templates will look like this:

<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:

The Answer:

1) <th:block></th:block> makes no diffrence

2) The additions to the html tag

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"

make no difference

3) placing the script-tags with content at the bottom of the body is the same as when placing it in the head

4) I use Bootstrap in this project and used the datepicker inside a div of Bootstrap. After placing it somewhere else in the body and not inside a div it worked.

Conclusion: If you are using Spring MVC and Thymeleaf and want to include JavaScript files you need:

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) Make sure your JS or CSS files are not "overwritten" by following files

Thanks for your time and help @Parth!